From 9c3b49078035dbb8caa0a10bffcdf1d27b8877ab Mon Sep 17 00:00:00 2001 From: simplenty <52663614+simplenty@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:21:48 +0000 Subject: [PATCH 1/2] Release the first version Publish the first public release built from the develop tree. --- .github/workflows/ci.yml | 17 +- .github/workflows/codeql.yml | 2 +- .github/workflows/release.yml | 20 +- .gitignore | 1 + CHANGELOG.md | 377 +- CONTRIBUTING.md | 29 +- Directory.Build.props | 6 + Directory.Packages.props | 1 + README.md | 32 +- THIRD-PARTY-LICENSES.md | 2 +- apps/windows/Keepassity.App/AboutPanel.xaml | 42 + .../windows/Keepassity.App/AboutPanel.xaml.cs | 30 + apps/windows/Keepassity.App/App.xaml | 129 + .../App.xaml.cs | 64 +- .../AppAssets.cs | 4 +- .../AppSelfTest.cs | 165 +- .../Assets/app-icon-256.png | Bin .../Assets/app-icon-512.png | Bin .../Assets/app-icon.svg | 0 .../Assets/app.ico | Bin .../Keepassity.App/CoreClient.Groups.cs | 137 + .../Keepassity.App/CoreClient.SaveSync.cs | 202 + .../Keepassity.App/CoreClient.Settings.cs | 113 + .../Keepassity.App/CoreClient.TotpPassword.cs | 85 + apps/windows/Keepassity.App/CoreClient.cs | 203 + apps/windows/Keepassity.App/CoreTotpSource.cs | 20 + .../Keepassity.App/DatabaseSettingsPanel.xaml | 307 + .../DatabaseSettingsPanel.xaml.cs | 103 + .../Keepassity.App/EntryRowPresenter.cs | 39 + .../Keepassity.App.csproj} | 26 +- .../LaunchArguments.cs | 2 +- .../Keepassity.App/LiveVaultDocument.cs | 29 + .../Keepassity.App/Localization/Loc.cs | 255 + .../Keepassity.App/Localization/LocMarkup.cs | 247 + .../Keepassity.App/Localization/LocText.cs | 18 + .../Keepassity.App/MainWindow.About.cs | 270 + .../MainWindow.Accessibility.cs | 96 + .../Keepassity.App/MainWindow.Certificates.cs | 138 + .../Keepassity.App/MainWindow.DragDrop.cs | 159 + .../Keepassity.App/MainWindow.Encryption.cs | 300 + .../Keepassity.App/MainWindow.EntryDetail.cs | 247 + .../Keepassity.App/MainWindow.EntryEditor.cs | 364 + .../MainWindow.EntryFormControls.cs | 174 + .../Keepassity.App/MainWindow.EntryList.cs | 279 + .../MainWindow.EntryListEvents.cs | 196 + .../MainWindow.GroupDragDrop.cs | 173 + .../MainWindow.LegacyProfile.cs | 526 ++ .../Keepassity.App/MainWindow.Localization.cs | 235 + .../Keepassity.App/MainWindow.Navigation.cs | 325 + .../Keepassity.App/MainWindow.Network.cs | 361 + .../Keepassity.App/MainWindow.NewDatabase.cs | 401 ++ .../windows/Keepassity.App/MainWindow.Pane.cs | 235 + .../Keepassity.App/MainWindow.Panels.cs | 377 + .../MainWindow.PasswordGenerator.cs | 274 + .../MainWindow.RecentDatabases.cs | 134 + .../Keepassity.App/MainWindow.SessionLock.cs | 114 + .../MainWindow.SettingsForms.cs | 182 + .../Keepassity.App/MainWindow.SettingsPage.cs | 131 + .../Keepassity.App/MainWindow.Shell.cs | 177 + .../Keepassity.App/MainWindow.Shortcuts.cs | 138 + .../MainWindow.SingleInstance.cs | 66 + .../Keepassity.App/MainWindow.SyncDialogs.cs | 328 + .../Keepassity.App/MainWindow.SyncRun.cs | 172 + .../Keepassity.App/MainWindow.SyncStatus.cs | 53 + .../Keepassity.App/MainWindow.TotpSetup.cs | 206 + .../Keepassity.App/MainWindow.Unlock.cs | 196 + .../MainWindow.UnlockRecovery.cs | 212 + .../Keepassity.App/MainWindow.Vault.cs | 245 + .../Keepassity.App/MainWindow.VaultIo.cs | 119 + .../Keepassity.App/MainWindow.WebDavOpen.cs | 356 + .../Keepassity.App/MainWindow.WindowAssets.cs | 89 + .../MainWindow.xaml | 305 +- .../windows/Keepassity.App/MainWindow.xaml.cs | 87 + .../QrDecoder.cs | 2 +- .../README.md | 23 +- .../SessionLockMonitor.cs | 2 +- apps/windows/Keepassity.App/SettingsPage.xaml | 99 + .../Keepassity.App/SettingsPage.xaml.cs | 78 + .../windows/Keepassity.App/SettingsPanel.xaml | 155 + .../Keepassity.App/SettingsPanel.xaml.cs | 55 + .../SingleInstanceRelay.Forward.cs | 164 + .../SingleInstanceRelay.Window.cs | 136 + .../Keepassity.App/SingleInstanceRelay.cs | 170 + .../TestHooks.cs | 7 +- apps/windows/Keepassity.App/TrayIcon.Icon.cs | 58 + apps/windows/Keepassity.App/TrayIcon.Menu.cs | 294 + apps/windows/Keepassity.App/TrayIcon.State.cs | 100 + apps/windows/Keepassity.App/TrayIcon.cs | 239 + .../app.manifest | 0 .../packages.lock.json | 32 +- apps/windows/Keepassity.Core/AppLog.cs | 37 +- .../Keepassity.Core/AppSettingsStore.cs | 103 +- .../{AppDataPaths.cs => ApplicationPaths.cs} | 4 +- apps/windows/Keepassity.Core/AtomicFile.cs | 299 + apps/windows/Keepassity.Core/BackupService.cs | 186 +- .../Keepassity.Core/CertificateTrust.cs | 74 + apps/windows/Keepassity.Core/CoreDtos.cs | 179 + apps/windows/Keepassity.Core/CoreException.cs | 17 + .../Keepassity.Core/CredentialStore.cs | 42 +- .../Keepassity.Core/DiagnosticsService.cs | 126 +- apps/windows/Keepassity.Core/ICoreClient.cs | 101 + apps/windows/Keepassity.Core/ISyncRemote.cs | 28 + .../windows/Keepassity.Core/IVaultDocument.cs | 32 + apps/windows/Keepassity.Core/KdfCommands.cs | 44 + .../Keepassity.Core/Keepassity.Core.csproj | 14 +- .../Localization/LocalizationCatalog.cs | 166 + .../Localization/ui.zh-CN.json | 224 + .../Localization/window.zh-CN.json | 237 + apps/windows/Keepassity.Core/LogFile.cs | 128 + .../Keepassity.Core/NewDatabasePreparer.cs | 71 + .../RecentDatabaseStore.cs | 42 +- .../Keepassity.Core/RemoteCacheCleaner.cs | 186 + .../Keepassity.Core/RemoteDatabaseStore.cs | 94 +- .../Keepassity.Core/RemoteVaultOpener.cs | 106 + apps/windows/Keepassity.Core/RunStateStore.cs | 134 + .../SyncCoordinator.ConflictCopies.cs | 106 + .../SyncCoordinator.Download.cs | 195 + .../Keepassity.Core/SyncCoordinator.Repair.cs | 146 + .../Keepassity.Core/SyncCoordinator.Upload.cs | 109 + .../Keepassity.Core/SyncCoordinator.cs | 307 + .../windows/Keepassity.Core/SyncStateStore.cs | 101 +- .../Keepassity.Core/TrayMenuPlacement.cs | 2 +- apps/windows/Keepassity.Core/VaultFileLock.cs | 196 + .../Keepassity.Core/VaultFingerprint.cs | 27 + .../Keepassity.Core/VaultProfileStore.cs | 218 + apps/windows/Keepassity.Core/VaultRecovery.cs | 56 + apps/windows/Keepassity.Core/VaultSession.cs | 344 + .../windows/Keepassity.Core/VaultWriteGate.cs | 34 + apps/windows/Keepassity.Core/WebDavClient.cs | 139 +- apps/windows/Keepassity.Core/WebDavTls.cs | 2 +- .../Keepassity.Core/packages.lock.json | 7 - apps/windows/Keepassity.Mock/App.xaml | 51 - apps/windows/Keepassity.Mock/CoreClient.cs | 724 -- .../Keepassity.Mock/MainWindow.xaml.cs | 6120 ----------------- .../Keepassity.Mock/SingleInstanceRelay.cs | 447 -- apps/windows/Keepassity.Mock/TrayIcon.cs | 605 -- .../AccessibilityText.cs | 32 + .../DatabaseSettingsViewModel.cs | 164 + .../DropTargetResolver.cs | 56 + .../EncryptionViewModel.cs | 137 + .../EntryDetailViewModel.cs | 149 + .../EntryEditorViewModel.cs | 120 + .../EntryListProjection.cs | 64 + .../Keepassity.ViewModels/EntryRowInput.cs | 17 + .../EntryRowViewModel.cs | 91 + .../Keepassity.ViewModels/GroupNavItem.cs | 23 + .../GroupNavigationProjection.cs | 62 + .../windows/Keepassity.ViewModels/IAppText.cs | 19 + .../Keepassity.ViewModels.csproj | 15 + .../NetworkReplayPolicy.cs | 54 + .../RecentDatabaseList.cs | 53 + .../Keepassity.ViewModels/SettingsHost.cs | 47 + .../SettingsViewModel.cs | 315 + .../SyncStatusViewModel.cs | 45 + .../TotpDisplayViewModel.cs | 281 + .../Keepassity.ViewModels/TotpTiming.cs | 67 + .../Keepassity.ViewModels/UnlockViewModel.cs | 245 + apps/windows/Keepassity.sln | 16 +- crates/cli/src/kdf.rs | 233 + crates/cli/src/main.rs | 4 + crates/cli/src/verify.rs | 546 -- crates/cli/src/verify/compare.rs | 224 + crates/cli/src/verify/dump.rs | 229 + crates/cli/src/verify/io.rs | 35 + crates/cli/src/verify/mod.rs | 78 + crates/core/src/dto/entry.rs | 147 + crates/core/src/dto/error.rs | 45 + crates/core/src/dto/mod.rs | 384 +- crates/core/src/dto/sync.rs | 110 + crates/core/src/dto/totp.rs | 88 + crates/core/src/kdbx/reader.rs | 711 -- crates/core/src/kdbx/reader/convert.rs | 241 + crates/core/src/kdbx/reader/error.rs | 65 + crates/core/src/kdbx/reader/header.rs | 129 + crates/core/src/kdbx/reader/limits.rs | 248 + crates/core/src/kdbx/reader/mod.rs | 360 + crates/core/src/kdbx/reader/parse.rs | 63 + crates/core/src/kdbx/reader/parser.rs | 20 + crates/core/src/kdbx/writer.rs | 269 - crates/core/src/kdbx/writer/backend.rs | 137 + crates/core/src/kdbx/writer/create.rs | 56 + crates/core/src/kdbx/writer/mod.rs | 105 + crates/core/src/kdbx/writer/save.rs | 193 + crates/core/src/kdbx/writer/xml.rs | 232 + crates/core/src/merge/choice.rs | 269 + crates/core/src/merge/deletion.rs | 253 + crates/core/src/merge/index.rs | 79 + crates/core/src/merge/mod.rs | 644 +- crates/core/src/merge/tests.rs | 211 + crates/core/src/model/database.rs | 122 + crates/core/src/model/entry.rs | 187 + crates/core/src/model/group.rs | 62 + crates/core/src/model/meta.rs | 195 + crates/core/src/model/mod.rs | 630 +- crates/core/src/model/outer.rs | 251 + crates/core/src/model/rawxml.rs | 30 + crates/core/src/model/time.rs | 120 + crates/core/src/model/uuid.rs | 83 + crates/core/tests/kdf_defaults.rs | 65 +- crates/core/tests/kdf_edit.rs | 144 + crates/core/tests/malformed_input.rs | 76 + crates/core/tests/merge_history_deletions.rs | 337 + crates/core/tests/merge_write.rs | 9 +- crates/core/tests/model_dto.rs | 1 + crates/core/tests/synthetic_fixture.rs | 1 + crates/core/tests/writer_fidelity.rs | 287 + crates/core/tests/writer_header.rs | 98 + crates/ffi/src/abi.rs | 451 ++ crates/ffi/src/dispatch.rs | 379 + crates/ffi/src/json_helpers.rs | 172 + crates/ffi/src/lib.rs | 1528 +--- crates/ffi/src/model_helpers.rs | 329 + crates/ffi/src/password.rs | 94 + crates/ffi/src/tests/entries.rs | 191 + crates/ffi/src/tests/helpers.rs | 70 + crates/ffi/src/tests/mod.rs | 17 + crates/ffi/src/tests/recycle.rs | 213 + crates/ffi/src/tests/surface.rs | 97 + crates/ffi/src/tests/sync_kdf.rs | 244 + crates/ffi/src/tests/totp_password.rs | 169 + crates/ffi/src/totp_helpers.rs | 85 + docs/architecture.md | 112 +- docs/compatibility.md | 44 +- docs/release.md | 39 +- docs/testing.md | 90 +- global.json | 4 +- installer/keepassity.iss | 45 +- public.allowlist | 6 +- scripts/check-structure.ps1 | 224 + scripts/make-checksums.ps1 | 17 +- scripts/publish-windows.ps1 | 10 +- scripts/selftest.ps1 | 4 +- scripts/structure-budget.json | 39 + scripts/test.ps1 | 35 +- scripts/verify-checksums.ps1 | 48 + scripts/verify-installer-runtime.ps1 | 225 + .../ArchitectureTests.cs | 324 + .../Keepassity.Core.Tests/AtomicFileTests.cs | 189 + .../BackupServiceTests.cs | 114 +- .../CertificateTrustTests.cs | 102 + .../DatabaseSettingsViewModelTests.cs | 149 + .../DiagnosticsServiceTests.cs | 126 + .../DropAndReplayPolicyTests.cs | 88 + .../EncryptionViewModelTests.cs | 107 + .../EntryDetailViewModelTests.cs | 80 + .../EntryEditorViewModelTests.cs | 72 + .../EntryListViewModelTests.cs | 88 + .../GroupNavigationTests.cs | 50 + .../Keepassity.Core.Tests/KdfCommandsTests.cs | 56 + .../Keepassity.Core.Tests.csproj | 3 +- .../LocalizationTests.cs | 137 + .../Keepassity.Core.Tests/LogFileTests.cs | 113 + .../NewDatabasePreparerTests.cs | 172 + .../app-core/Keepassity.Core.Tests/Program.cs | 77 +- .../RecentDatabaseTests.cs | 58 + .../RecentListProjectionTests.cs | 118 + .../RemoteCacheCleanerTests.cs | 189 + .../RemoteVaultOpenIntegrationTests.cs | 198 + .../RemoteVaultOpenerTests.cs | 312 + .../RunStateStoreTests.cs | 92 + .../SettingsAndCredentialTests.cs | 66 +- .../SettingsViewModelTests.cs | 186 + .../SyncCoordinatorTests.cs | 892 +++ .../SyncStateStoreTests.cs | 60 + .../SyncStatusViewModelTests.cs | 45 + .../TotpDisplayViewModelTests.cs | 135 + .../Keepassity.Core.Tests/TotpTimingTests.cs | 57 + .../UnlockViewModelTests.cs | 343 + .../VaultFileLockTests.cs | 108 + .../Keepassity.Core.Tests/VaultGuardTests.cs | 50 + .../VaultProfileStoreTests.cs | 136 + .../VaultRecoveryTests.cs | 194 + .../VaultSessionTests.cs | 481 ++ .../VaultWriteGateTests.cs | 48 + .../WebDavNonAsciiPathTests.cs | 52 +- .../WebDavSafetyTests.cs | 124 + .../WebDavTimeoutTests.cs | 138 + .../Keepassity.Core.Tests/WebDavTlsTests.cs | 4 +- .../Keepassity.Core.Tests/packages.lock.json | 15 +- tests/ffi-csharp/FfiSmoke.csproj | 2 +- tests/ffi-csharp/packages.lock.json | 2 +- ..._db_kdbx4_with_password_argon2id.kdbx.lock | 0 tools/check-localization.ps1 | 1668 +++++ tools/check-ui-strings.ps1 | 18 +- tools/drills/README.md | 6 +- tools/drills/_common.ps1 | 4 +- tools/drills/mock-webdav/MockWebDav.csproj | 2 +- tools/drills/runner/DrillRunner.csproj | 2 +- tools/drills/runner/Drills.cs | 2 +- tools/drills/runner/Program.cs | 2 +- tools/icon/make-app-icon.py | 8 +- tools/installer/verify-install.ps1 | 14 +- vendor/keepassxcr/src/crypto/kdf.rs | 22 +- vendor/keepassxcr/src/format/kdbx.rs | 107 +- vendor/keepassxcr/src/format/mod.rs | 4 +- 295 files changed, 36535 insertions(+), 13006 deletions(-) create mode 100644 apps/windows/Keepassity.App/AboutPanel.xaml create mode 100644 apps/windows/Keepassity.App/AboutPanel.xaml.cs create mode 100644 apps/windows/Keepassity.App/App.xaml rename apps/windows/{Keepassity.Mock => Keepassity.App}/App.xaml.cs (74%) rename apps/windows/{Keepassity.Mock => Keepassity.App}/AppAssets.cs (86%) rename apps/windows/{Keepassity.Mock => Keepassity.App}/AppSelfTest.cs (60%) rename apps/windows/{Keepassity.Mock => Keepassity.App}/Assets/app-icon-256.png (100%) rename apps/windows/{Keepassity.Mock => Keepassity.App}/Assets/app-icon-512.png (100%) rename apps/windows/{Keepassity.Mock => Keepassity.App}/Assets/app-icon.svg (100%) rename apps/windows/{Keepassity.Mock => Keepassity.App}/Assets/app.ico (100%) create mode 100644 apps/windows/Keepassity.App/CoreClient.Groups.cs create mode 100644 apps/windows/Keepassity.App/CoreClient.SaveSync.cs create mode 100644 apps/windows/Keepassity.App/CoreClient.Settings.cs create mode 100644 apps/windows/Keepassity.App/CoreClient.TotpPassword.cs create mode 100644 apps/windows/Keepassity.App/CoreClient.cs create mode 100644 apps/windows/Keepassity.App/CoreTotpSource.cs create mode 100644 apps/windows/Keepassity.App/DatabaseSettingsPanel.xaml create mode 100644 apps/windows/Keepassity.App/DatabaseSettingsPanel.xaml.cs create mode 100644 apps/windows/Keepassity.App/EntryRowPresenter.cs rename apps/windows/{Keepassity.Mock/Keepassity.Mock.csproj => Keepassity.App/Keepassity.App.csproj} (78%) rename apps/windows/{Keepassity.Mock => Keepassity.App}/LaunchArguments.cs (98%) create mode 100644 apps/windows/Keepassity.App/LiveVaultDocument.cs create mode 100644 apps/windows/Keepassity.App/Localization/Loc.cs create mode 100644 apps/windows/Keepassity.App/Localization/LocMarkup.cs create mode 100644 apps/windows/Keepassity.App/Localization/LocText.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.About.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.Accessibility.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.Certificates.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.DragDrop.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.Encryption.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.EntryDetail.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.EntryEditor.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.EntryFormControls.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.EntryList.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.EntryListEvents.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.GroupDragDrop.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.LegacyProfile.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.Localization.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.Navigation.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.Network.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.NewDatabase.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.Pane.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.Panels.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.PasswordGenerator.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.RecentDatabases.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.SessionLock.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.SettingsForms.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.SettingsPage.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.Shell.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.Shortcuts.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.SingleInstance.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.SyncDialogs.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.SyncRun.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.SyncStatus.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.TotpSetup.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.Unlock.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.UnlockRecovery.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.Vault.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.VaultIo.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.WebDavOpen.cs create mode 100644 apps/windows/Keepassity.App/MainWindow.WindowAssets.cs rename apps/windows/{Keepassity.Mock => Keepassity.App}/MainWindow.xaml (76%) create mode 100644 apps/windows/Keepassity.App/MainWindow.xaml.cs rename apps/windows/{Keepassity.Mock => Keepassity.App}/QrDecoder.cs (98%) rename apps/windows/{Keepassity.Mock => Keepassity.App}/README.md (84%) rename apps/windows/{Keepassity.Mock => Keepassity.App}/SessionLockMonitor.cs (99%) create mode 100644 apps/windows/Keepassity.App/SettingsPage.xaml create mode 100644 apps/windows/Keepassity.App/SettingsPage.xaml.cs create mode 100644 apps/windows/Keepassity.App/SettingsPanel.xaml create mode 100644 apps/windows/Keepassity.App/SettingsPanel.xaml.cs create mode 100644 apps/windows/Keepassity.App/SingleInstanceRelay.Forward.cs create mode 100644 apps/windows/Keepassity.App/SingleInstanceRelay.Window.cs create mode 100644 apps/windows/Keepassity.App/SingleInstanceRelay.cs rename apps/windows/{Keepassity.Mock => Keepassity.App}/TestHooks.cs (87%) create mode 100644 apps/windows/Keepassity.App/TrayIcon.Icon.cs create mode 100644 apps/windows/Keepassity.App/TrayIcon.Menu.cs create mode 100644 apps/windows/Keepassity.App/TrayIcon.State.cs create mode 100644 apps/windows/Keepassity.App/TrayIcon.cs rename apps/windows/{Keepassity.Mock => Keepassity.App}/app.manifest (100%) rename apps/windows/{Keepassity.Mock => Keepassity.App}/packages.lock.json (91%) rename apps/windows/Keepassity.Core/{AppDataPaths.cs => ApplicationPaths.cs} (94%) create mode 100644 apps/windows/Keepassity.Core/AtomicFile.cs create mode 100644 apps/windows/Keepassity.Core/CertificateTrust.cs create mode 100644 apps/windows/Keepassity.Core/CoreDtos.cs create mode 100644 apps/windows/Keepassity.Core/CoreException.cs create mode 100644 apps/windows/Keepassity.Core/ICoreClient.cs create mode 100644 apps/windows/Keepassity.Core/ISyncRemote.cs create mode 100644 apps/windows/Keepassity.Core/IVaultDocument.cs create mode 100644 apps/windows/Keepassity.Core/KdfCommands.cs create mode 100644 apps/windows/Keepassity.Core/Localization/LocalizationCatalog.cs create mode 100644 apps/windows/Keepassity.Core/Localization/ui.zh-CN.json create mode 100644 apps/windows/Keepassity.Core/Localization/window.zh-CN.json create mode 100644 apps/windows/Keepassity.Core/LogFile.cs create mode 100644 apps/windows/Keepassity.Core/NewDatabasePreparer.cs rename apps/windows/{Keepassity.Mock => Keepassity.Core}/RecentDatabaseStore.cs (75%) create mode 100644 apps/windows/Keepassity.Core/RemoteCacheCleaner.cs create mode 100644 apps/windows/Keepassity.Core/RemoteVaultOpener.cs create mode 100644 apps/windows/Keepassity.Core/RunStateStore.cs create mode 100644 apps/windows/Keepassity.Core/SyncCoordinator.ConflictCopies.cs create mode 100644 apps/windows/Keepassity.Core/SyncCoordinator.Download.cs create mode 100644 apps/windows/Keepassity.Core/SyncCoordinator.Repair.cs create mode 100644 apps/windows/Keepassity.Core/SyncCoordinator.Upload.cs create mode 100644 apps/windows/Keepassity.Core/SyncCoordinator.cs create mode 100644 apps/windows/Keepassity.Core/VaultFileLock.cs create mode 100644 apps/windows/Keepassity.Core/VaultFingerprint.cs create mode 100644 apps/windows/Keepassity.Core/VaultProfileStore.cs create mode 100644 apps/windows/Keepassity.Core/VaultRecovery.cs create mode 100644 apps/windows/Keepassity.Core/VaultSession.cs create mode 100644 apps/windows/Keepassity.Core/VaultWriteGate.cs delete mode 100644 apps/windows/Keepassity.Core/packages.lock.json delete mode 100644 apps/windows/Keepassity.Mock/App.xaml delete mode 100644 apps/windows/Keepassity.Mock/CoreClient.cs delete mode 100644 apps/windows/Keepassity.Mock/MainWindow.xaml.cs delete mode 100644 apps/windows/Keepassity.Mock/SingleInstanceRelay.cs delete mode 100644 apps/windows/Keepassity.Mock/TrayIcon.cs create mode 100644 apps/windows/Keepassity.ViewModels/AccessibilityText.cs create mode 100644 apps/windows/Keepassity.ViewModels/DatabaseSettingsViewModel.cs create mode 100644 apps/windows/Keepassity.ViewModels/DropTargetResolver.cs create mode 100644 apps/windows/Keepassity.ViewModels/EncryptionViewModel.cs create mode 100644 apps/windows/Keepassity.ViewModels/EntryDetailViewModel.cs create mode 100644 apps/windows/Keepassity.ViewModels/EntryEditorViewModel.cs create mode 100644 apps/windows/Keepassity.ViewModels/EntryListProjection.cs create mode 100644 apps/windows/Keepassity.ViewModels/EntryRowInput.cs create mode 100644 apps/windows/Keepassity.ViewModels/EntryRowViewModel.cs create mode 100644 apps/windows/Keepassity.ViewModels/GroupNavItem.cs create mode 100644 apps/windows/Keepassity.ViewModels/GroupNavigationProjection.cs create mode 100644 apps/windows/Keepassity.ViewModels/IAppText.cs create mode 100644 apps/windows/Keepassity.ViewModels/Keepassity.ViewModels.csproj create mode 100644 apps/windows/Keepassity.ViewModels/NetworkReplayPolicy.cs create mode 100644 apps/windows/Keepassity.ViewModels/RecentDatabaseList.cs create mode 100644 apps/windows/Keepassity.ViewModels/SettingsHost.cs create mode 100644 apps/windows/Keepassity.ViewModels/SettingsViewModel.cs create mode 100644 apps/windows/Keepassity.ViewModels/SyncStatusViewModel.cs create mode 100644 apps/windows/Keepassity.ViewModels/TotpDisplayViewModel.cs create mode 100644 apps/windows/Keepassity.ViewModels/TotpTiming.cs create mode 100644 apps/windows/Keepassity.ViewModels/UnlockViewModel.cs create mode 100644 crates/cli/src/kdf.rs delete mode 100644 crates/cli/src/verify.rs create mode 100644 crates/cli/src/verify/compare.rs create mode 100644 crates/cli/src/verify/dump.rs create mode 100644 crates/cli/src/verify/io.rs create mode 100644 crates/cli/src/verify/mod.rs create mode 100644 crates/core/src/dto/entry.rs create mode 100644 crates/core/src/dto/error.rs create mode 100644 crates/core/src/dto/sync.rs create mode 100644 crates/core/src/dto/totp.rs delete mode 100644 crates/core/src/kdbx/reader.rs create mode 100644 crates/core/src/kdbx/reader/convert.rs create mode 100644 crates/core/src/kdbx/reader/error.rs create mode 100644 crates/core/src/kdbx/reader/header.rs create mode 100644 crates/core/src/kdbx/reader/limits.rs create mode 100644 crates/core/src/kdbx/reader/mod.rs create mode 100644 crates/core/src/kdbx/reader/parse.rs create mode 100644 crates/core/src/kdbx/reader/parser.rs delete mode 100644 crates/core/src/kdbx/writer.rs create mode 100644 crates/core/src/kdbx/writer/backend.rs create mode 100644 crates/core/src/kdbx/writer/create.rs create mode 100644 crates/core/src/kdbx/writer/mod.rs create mode 100644 crates/core/src/kdbx/writer/save.rs create mode 100644 crates/core/src/kdbx/writer/xml.rs create mode 100644 crates/core/src/merge/choice.rs create mode 100644 crates/core/src/merge/deletion.rs create mode 100644 crates/core/src/merge/index.rs create mode 100644 crates/core/src/merge/tests.rs create mode 100644 crates/core/src/model/database.rs create mode 100644 crates/core/src/model/entry.rs create mode 100644 crates/core/src/model/group.rs create mode 100644 crates/core/src/model/meta.rs create mode 100644 crates/core/src/model/outer.rs create mode 100644 crates/core/src/model/rawxml.rs create mode 100644 crates/core/src/model/time.rs create mode 100644 crates/core/src/model/uuid.rs create mode 100644 crates/core/tests/kdf_edit.rs create mode 100644 crates/core/tests/merge_history_deletions.rs create mode 100644 crates/core/tests/writer_fidelity.rs create mode 100644 crates/core/tests/writer_header.rs create mode 100644 crates/ffi/src/abi.rs create mode 100644 crates/ffi/src/dispatch.rs create mode 100644 crates/ffi/src/json_helpers.rs create mode 100644 crates/ffi/src/model_helpers.rs create mode 100644 crates/ffi/src/password.rs create mode 100644 crates/ffi/src/tests/entries.rs create mode 100644 crates/ffi/src/tests/helpers.rs create mode 100644 crates/ffi/src/tests/mod.rs create mode 100644 crates/ffi/src/tests/recycle.rs create mode 100644 crates/ffi/src/tests/surface.rs create mode 100644 crates/ffi/src/tests/sync_kdf.rs create mode 100644 crates/ffi/src/tests/totp_password.rs create mode 100644 crates/ffi/src/totp_helpers.rs create mode 100644 scripts/check-structure.ps1 create mode 100644 scripts/structure-budget.json create mode 100644 scripts/verify-checksums.ps1 create mode 100644 scripts/verify-installer-runtime.ps1 create mode 100644 tests/app-core/Keepassity.Core.Tests/ArchitectureTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/AtomicFileTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/CertificateTrustTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/DatabaseSettingsViewModelTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/DiagnosticsServiceTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/DropAndReplayPolicyTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/EncryptionViewModelTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/EntryDetailViewModelTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/EntryEditorViewModelTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/EntryListViewModelTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/GroupNavigationTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/KdfCommandsTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/LocalizationTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/LogFileTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/NewDatabasePreparerTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/RecentDatabaseTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/RecentListProjectionTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/RemoteCacheCleanerTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/RemoteVaultOpenIntegrationTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/RemoteVaultOpenerTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/RunStateStoreTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/SettingsViewModelTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/SyncCoordinatorTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/SyncStateStoreTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/SyncStatusViewModelTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/TotpDisplayViewModelTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/TotpTimingTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/UnlockViewModelTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/VaultFileLockTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/VaultGuardTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/VaultProfileStoreTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/VaultRecoveryTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/VaultSessionTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/VaultWriteGateTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/WebDavSafetyTests.cs create mode 100644 tests/app-core/Keepassity.Core.Tests/WebDavTimeoutTests.cs create mode 100644 tests/fixtures/keepass-rs/.keepassity/locks/test_db_kdbx4_with_password_argon2id.kdbx.lock create mode 100644 tools/check-localization.ps1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f547560..f4f2c2d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -79,7 +79,7 @@ jobs: - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - uses: actions/setup-dotnet@67a3573c9a986a3f9c594539f4ab511d57bb3ce9 # v4.3.1 with: - dotnet-version: "8.0.x" + dotnet-version: "10.0.x" - name: download and verify the official KeePass source release shell: pwsh # SourceForge is the only official distributor and it rejects @@ -214,7 +214,7 @@ jobs: - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - uses: actions/setup-dotnet@67a3573c9a986a3f9c594539f4ab511d57bb3ce9 # v4.3.1 with: - dotnet-version: "8.0.x" + dotnet-version: "10.0.x" - name: Linux build deps (hidapi/udev) run: sudo apt-get update && sudo apt-get install -y libudev-dev pkg-config - name: build FFI library @@ -243,7 +243,7 @@ jobs: - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - uses: actions/setup-dotnet@67a3573c9a986a3f9c594539f4ab511d57bb3ce9 # v4.3.1 with: - dotnet-version: "8.0.x" + dotnet-version: "10.0.x" - name: build FFI library run: cargo build -p keepassity-ffi --release - name: restore and build the app @@ -252,6 +252,8 @@ jobs: /p:KeepassityFfiDir=${{ github.workspace }}\target\release\ - name: core service tests run: dotnet run --project tests/app-core/Keepassity.Core.Tests -c Release + - name: structure budget (ADR-0035) + run: powershell -NoProfile -ExecutionPolicy Bypass -File scripts/check-structure.ps1 - name: application self-test shell: pwsh run: | @@ -259,7 +261,7 @@ jobs: @{ fixture = 'tests/fixtures/keepass-rs/test_db_kdbx4_with_password_aes.kdbx'; password = 'demopass' }, @{ fixture = 'tests/fixtures/keepass-rs/test_db_kdbx4_with_totp_entry.kdbx'; password = 'test' } ) - $exe = (Get-ChildItem 'apps/windows/Keepassity.Mock/bin' -Recurse -Filter 'Keepassity.exe' | + $exe = (Get-ChildItem 'apps/windows/Keepassity.App/bin' -Recurse -Filter 'Keepassity.exe' | Where-Object { $_.FullName -match '\\Release\\' } | Select-Object -First 1).FullName foreach ($case in $cases) { $report = Join-Path $env:RUNNER_TEMP ('selftest-' + [guid]::NewGuid().ToString('N') + '.log') @@ -279,16 +281,19 @@ jobs: - name: dependency audit (informational) shell: pwsh continue-on-error: true - run: dotnet list apps/windows/Keepassity.Mock/Keepassity.Mock.csproj package --vulnerable --include-transitive + run: dotnet list apps/windows/Keepassity.App/Keepassity.App.csproj package --vulnerable --include-transitive ui-strings: name: ui-strings / ubuntu runs-on: ubuntu-latest steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - name: reject hard-coded CJK text in the English UI + - name: reject hard-coded CJK text in the shell sources shell: pwsh run: ./tools/check-ui-strings.ps1 + - name: check UI language catalogs and key usage + shell: pwsh + run: ./tools/check-localization.ps1 -Strict secret-scan: name: secret-scan diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 9ca113e..e5b26ea 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -22,7 +22,7 @@ jobs: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - uses: actions/setup-dotnet@67a3573c9a986a3f9c594539f4ab511d57bb3ce9 # v4.3.1 with: - dotnet-version: "8.0.x" + dotnet-version: "10.0.x" - name: initialize CodeQL uses: github/codeql-action/init@9418214df1f2c4b8128c770156c409013b07d6b9 # v3.39.3 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cacc8f1..d8f4a0d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -25,7 +25,7 @@ jobs: - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - uses: actions/setup-dotnet@67a3573c9a986a3f9c594539f4ab511d57bb3ce9 # v4.3.1 with: - dotnet-version: "8.0.x" + dotnet-version: "10.0.x" - name: determine version shell: pwsh @@ -40,10 +40,16 @@ jobs: - name: verify the source shell: pwsh run: | + cargo fmt --all -- --check + if ($LASTEXITCODE -ne 0) { exit 1 } + cargo clippy --workspace --all-targets -- -D warnings + if ($LASTEXITCODE -ne 0) { exit 1 } cargo test --workspace if ($LASTEXITCODE -ne 0) { exit 1 } dotnet run --project tests/app-core/Keepassity.Core.Tests -c Release if ($LASTEXITCODE -ne 0) { exit 1 } + powershell -NoProfile -ExecutionPolicy Bypass -File scripts/check-public.ps1 + if ($LASTEXITCODE -ne 0) { exit 1 } powershell -NoProfile -ExecutionPolicy Bypass -File scripts/verify-fixtures.ps1 if ($LASTEXITCODE -ne 0) { exit 1 } @@ -90,10 +96,6 @@ jobs: -SourceDir "out/dist/keepassity-$env:KEEPASSITY_VERSION-win-x64" ` -OutputDir "out/dist" - - name: write checksums - shell: pwsh - run: powershell -NoProfile -ExecutionPolicy Bypass -File scripts/make-checksums.ps1 -Directory out/dist - - name: generate SBOM uses: anchore/sbom-action@e22c389904149dbc22b58101806040fa8d37a610 # v0.24.0 with: @@ -102,6 +104,14 @@ jobs: output-file: out/dist/sbom.spdx.json artifact-name: keepassity-sbom + - name: write checksums + shell: pwsh + run: powershell -NoProfile -ExecutionPolicy Bypass -File scripts/make-checksums.ps1 -Directory out/dist + + - name: verify checksums + shell: pwsh + run: powershell -NoProfile -ExecutionPolicy Bypass -File scripts/verify-checksums.ps1 -Directory out/dist + - name: attest build provenance uses: actions/attest-build-provenance@e8998f949152b193b063cb0ec769d69d929409be # v2.4.0 with: diff --git a/.gitignore b/.gitignore index 4f5cf3b..9c59f21 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ /target/ **/bin/ **/obj/ +/out/ .vs/ *.user *.suo diff --git a/CHANGELOG.md b/CHANGELOG.md index 8957820..7cd4570 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,8 +3,369 @@ All notable changes are documented here. Format: Keep a Changelog. Versioning: SemVer. KDBX write-path changes must state the compatibility impact. -## [Unreleased] +## [1.0.0] - 2026-12-01 +- **A save never rewrites the encryption parameters:** the outer header (format version, outer + cipher, compression, KDF, `PublicCustomData`) is carried through unchanged, and changing the KDF + is an explicit action instead of a side effect. A save that reuses the transformed-key cache can + no longer keep the previous parameters either: the backend takes the KDF from the cache, so the + writer now compares the cache with the header and derives again when they differ. Custom values + are validated against the reader's limits before anything is written, so the app cannot produce a + database it would refuse to open. The desktop app exposes this as read-only information plus an + explicit change dialog; nothing is migrated automatically. +- **New databases default to the interoperable Argon2id parameters (64 MiB / 3 / 2):** the previous + default (128 MiB / 6 / 4) was calibrated on the development machine and made a shared database + unusable on mobile clients, whose AutoFill extensions have a much smaller memory budget. The + stronger parameters remain available as an explicit desktop-only choice. +- **Encryption parameters are visible and changeable in the app:** a new "Encryption parameters" + page shows the values the file header carries and lists four presets — the KeePass 2.x default + (AES-KDF 600 000 rounds), the KeePassXC default profile (Argon2id 64 MiB / 3 / 2), a desktop-only + 128 MiB profile and a stronger 256 MiB one — with two columns only, encryption strength and + compatibility. Choosing a preset re-encrypts the database through the normal save path (backup, + verified write, atomic replace) and syncs afterwards; "Use the saved parameters" puts back what + the newest readable backup carries. Nothing is graded in the read-only area, nothing changes + without confirmation, and a database shared over WebDAV whose parameters exceed what mobile + clients open is mentioned once per session without blocking. +- **`keepassity-cli kdf`:** prints the parameters a file carries, and rewrites them explicitly + (`--set keepass-classic|keepassxc|desktop|strong|aes:|argon2id:::`, + or `--from-backup ` to restore the settings recorded in an earlier copy). The rewritten file + is read back and its header compared with the request before it is written. + +- **Creating a database uses the durable write protocol, and creating one on WebDAV works + again:** a new local database is written through a flushed temporary file and a create-only + move, so a file another program creates in the same moment is never replaced; a WebDAV create + claims the local working copy before the remote file exists, then writes the working copy + durably and records the clean sync baseline through `NewDatabasePreparer`. The flow had been + routed through the sync write guard with a path that was not the open vault (introduced with + the `VaultSession` consolidation), which made a WebDAV create fail after the upload. +- **Release builds no longer leave the repository dirty:** the two library projects stopped + generating their own `packages.lock.json`; their package graph is already pinned by the + application and test lock files, and the duplicated library locks flipped between a RID and a + non-RID restore, so every `scripts/publish-windows.ps1` run modified tracked files (and a plain + restore reported them as modified again because of line endings). +- **An incomplete upload is detected before it becomes the baseline:** a WebDAV server or proxy + can answer 2xx while storing fewer bytes than were sent (a cut stream, a size-limited proxy). + The client now reads back the stored size with a PROPFIND before reporting success; a short or + missing file raises an upload error, so the sync never records a clean baseline for a remote copy + that is already truncated. If a truncated remote is met later, the unreadable-remote recovery + path preserves and repairs it. +- **An unreadable remote copy can be repaired:** when the server-side database cannot be opened + with the master password (a failed upload from another client, a server-side truncation, a + different encryption), a sync used to fail and every later sync failed at the same point — the + local vault stayed safe but the remote copy remained broken with no way to fix it from the app. + The run now pauses without touching the local vault and offers an explicit repair dialog that + replaces the unreadable remote with the verified local copy; nothing is uploaded unless the user + confirms. Before that choice is offered, the exact remote bytes are preserved next to the local + database under a hash-derived name, so a damaged file — or a valid database protected by a + different master password from another device — is never lost by the repair. +- **Large vaults no longer time out during sync:** every WebDAV request shared the HTTP client's + fixed 45-second timeout, so a database with large attachments could not be downloaded or + uploaded on a slow link and the save failed on every attempt. Metadata requests keep the + 45-second bound, whole-file transfers now get thirty minutes, a stalled transfer still aborts + with a clear "timed out" message, and caller cancellation is still reported as cancellation. +- **Conflict copies no longer pile up across restarts:** the local/remote copies for an unresolved + conflict were named with the current timestamp, so every sync against the same unresolved pair + (or every launch after a cancelled dialog) wrote another pair into the vault folder, and a new + process could never match the older ones. Names now derive from the local and remote content + hashes and a sync locates and reuses the matching pair, including in a fresh process with no + in-memory state. A same-named file with different bytes is never overwritten; the new copy gets + a numeric suffix. +- **The last write is guarded too:** a save, sync replacement or backup restore checked that + the file had not changed outside Keepassity, then wrote it; another program changing the file in + the gap (core serialization, KDF, temporary write, backup copy — seconds for a large vault) could + still be overwritten. The replace step now takes a last-moment check after the backup is taken + and immediately before the rename: a changed database aborts with `VaultChanged`, the temporary + is removed, and the live file plus the fresh recovery backup are kept. +- **Logs are bounded and no longer lose lines to sharing:** one day's log could grow without + limit (an error loop could fill the disk), a second instance's append failed on a sharing + violation, and the diagnostics exporter could fail to read the newest log while the app was + writing it. Daily logs now rotate to a single `.1` sibling at 5 MB, pruning enforces both the + fourteen-day window and a 50 MB folder ceiling, and every handle shares read/write/delete so + appends and diagnostics exports always see the current file. +- **Crash residue is cleaned up:** a crash during a backup copy, a backup restore or a sidecar + write could leave `.tmp-` / `.keepassity-tmp-` files behind forever; only the save temporaries + next to the database were cleaned when a vault was opened. Opening a vault now also removes + crash-left restore and backup temporaries, and the first launch of the day removes stale + protocol temporaries anywhere under the application data folder (fresh files are kept, so a + concurrent test instance is never disturbed). +- **A save during a sync is no longer overwritten:** a background sync captured the local file + when it started and then replaced it with downloaded or merged bytes after the network round + trip, so a save that landed in between could be silently undone and the reloaded window would + show the reverted data. The coordinator now remembers the run's local file hash (updated when it + writes the file itself) and checks it before every replace and before writing an upload + snapshot: the newer local save is kept, the vault stays dirty and the next sync merges both + sides. Fake-network scenarios cover the download, merge and upload paths. +- **Diagnostics exports are durable, unique and bounded:** two exports in the same second collided + on the archive name (the second one failed), the finished zip was moved into place without a + disk flush, and every export stayed in the data folder forever. The archive now carries a + millisecond timestamp with a unique fallback suffix, is written to a flushed temporary and moved + atomically, crash-left `.tmp` files are removed, and only the newest ten archives are kept. +- **The WebDAV cache stays bounded:** every remote database ever opened left its working copy and + up to twenty backups under the application data folder, and nothing removed them. A startup pass + now drops clean working copies that have not been touched for ninety days (they can be downloaded + again), plus backups, metadata and sync state whose working copy already vanished. Copies with + unsynced edits, copies whose hash does not match the recorded baseline, copies without source + metadata and the current target are never removed, and the recent-databases list forgets a + working copy that the pass deleted instead of offering that now-missing file on the unlock + screen. The pass only runs when this process owns the single-instance mutex before any window + opens. +- **A crash is noticed on the next launch:** a small run marker is written when the window + starts and removed on a clean close. When it is still there and its process is gone, the unlock + surface reports that the previous session ended unexpectedly and points at the backups, so a + crash or power loss no longer looks like a normal start. A marker from a still-running instance + is ignored, a malformed marker counts as an unclean run, and writing the marker is atomic and + best effort (the `--selftest` path never creates one). +- **Saves work on FAT/exFAT and network shares:** the atomic replace used `File.Replace`, which + is unavailable on volumes without that primitive, so every save of a vault on such a volume + failed. The placement now falls back to a same-volume rename (still a rename, so a crash leaves + either the old or the new complete database) with the backup taken just before as the recovery + point; the backup-restore path uses the same fallback. +- **Shared-folder vaults coordinate across machines and Windows accounts:** the lock lived only + under the per-account application data folder, so two machines or two Windows users opening the + same database on a network share could both hold it and silently overwrite each other's saves. + A writable vault folder now also holds an exclusive `.lock` inside its + `.keepassity/locks` folder; a lock held there refuses the open, releasing removes it, and the + OS drops it on a crash. A read-only folder keeps the account-only lock with a log entry. +- **A damaged database can be recovered from the unlock screen:** opening a corrupt database used + to leave only the error banner and an external backup-folder button, because the in-app backup + list needs an open vault. The unlock failure now offers the newest local backup that the entered + master password still opens; its bytes are verified with the core before anything is replaced, + the damaged file is kept as a before-restore backup, and the unlock is retried. Corrupt, + unreadable and wrong-password candidates are skipped (`VaultRecovery`). +- **Backup restore verifies the exact bytes it writes, and the self-test covers the round trip:** + the restore flow verified a backup by opening its path in a probe, so an external change between + the read and the probe could make it validate a different snapshot than the bytes it replaced. + It now runs `kp_verify` on the byte array that will be restored, before the pre-restore save and + the atomic replacement. The `--selftest` smoke test now creates a backup, makes and saves a + change, restores the backup, reopens and asserts that the change is gone and the overwritten + bytes survive as a recovery point. +- **A sync read can no longer make a save fail:** the sync coordinator read the live database file + directly, so its read handle could collide with a concurrent atomic replace and make the save + fail with a sharing violation. Reads now go through the vault session's write gate + (`ReadBytesAsync`), so a sync always hashes a complete database, a save never races the reader, + and the shutdown drain counts the read like any other in-flight operation. +- **A failing TOTP refresh cannot crash the window:** the display timer pulls the code from the + core, and a locked vault, a deleted entry or a rejected secret could throw out of the async + timer callback. The view model now catches the failed request, marks the code as unavailable + (the shell shows `TOTP code unavailable` instead of claiming no TOTP is configured) and lets the + next tick retry; the timer callback is also guarded as a last resort. +- **Locking waits for an in-flight save:** lock (manual button, tray menu, inactivity timer or a + Windows session event) used to lock the core immediately; a save that was already queued or + running then failed, leaving the previous complete file and losing the edit being written. Lock + now waits up to ten seconds for the vault session to finish writing; a manual or inactivity + lock stops with an informational message if the write is still stuck, while a session lock + proceeds anyway so a locked workstation never keeps an unlocked vault. A sync that reaches its + local replace phase after the vault locked now fails without touching the file instead of + replacing the database under a locked core. +- **A failed save keeps the session alive:** a disk or permission error no longer escapes the + save path (from an `async void` caller it could take the process down and with it the only + in-memory copy of the edit). The failure is logged and shown as an error toast, the in-memory + model keeps the change, the write gate is released, and the next successful save persists it. + Callers check the result so a success toast is not shown after a failed write, and the + backup-restore flow aborts instead of replacing the file when its pre-restore save fails. + Recording the dirty sync marker is best-effort now, so a sidecar IO error cannot turn a + successful save into a reported failure. +- **Closing the window waits for an in-flight vault write:** `VaultSession` now tracks queued and + running saves, sync replacements and restores, and the shell drains them (bounded to ten + seconds) before the closed handler releases the lock, disposes the write gate and the core. An + edit whose save was already running is therefore not the one cut off by exit; `AtomicFile` still + guarantees the file itself is always a complete database, and a write that outlives the drain no + longer has its gate disposed underneath it. +- **The WinUI shell project is `Keepassity.App`:** the prototype name `Keepassity.Mock` is gone + from the project folder, namespace, XAML classes, solution, publish/self-test scripts, + installer icon path, CI and docs; the shipped binary stays `Keepassity.exe`, and the pre-1.0 + `Keepassity.Mock.exe` cleanup in the installer/verify script is kept deliberately for upgrade + semantics. `Keepassity.Core` also gets its real root namespace. A clean self-contained + publish and an installer compile were run against the renamed project. +- **The publish script works under Windows PowerShell 5.1 again:** its version fallback read + `Directory.Build.props` through the PowerShell XML adapter, which returns an `XmlElement` + there, so the version property became `System.Xml.XmlElement`, restore failed with a + swallowed MSBuild error and the output folder was misnamed. The script now reads the DOM + `InnerText`; a clean self-contained publish and installer compile were verified afterwards. +- **Vault writes share one guard:** `VaultSession` in `Keepassity.Core` now owns the + cross-process lock, the in-process write gate and the content fingerprint, and exposes save, + sync-replace and backup-restore as the only write paths. The window no longer composes the + three guards by hand at each call site, so a save, a merge download and a restore cannot drift + into different safety rules. A locked vault also skips background sync instead of failing + against a locked core. The headless suite covers lock ownership, external-change refusal, + save serialization, atomic replacement with backup, restore ordering and release semantics + (29 checks). +- **A WebDAV download never replaces the vault before it is verified:** opening a database from + WebDAV now downloads the bytes into memory and keeps them pending; the master password opens + those exact bytes, and only then does `RemoteVaultOpener` write them to the local working copy + (durable atomic replace with a backup) and record a clean sync baseline. A wrong password, a + corrupted download or an HTML error page therefore leaves the previous working copy and its + baseline untouched, instead of clobbering the vault and requiring a backup restore. The + headless suite covers the ordering with fakes and adds an end-to-end check with the real core + and a loopback WebDAV server. +- **The WebDAV sync protocol is a tested application service:** `SyncCoordinator` in + `Keepassity.Core` now owns the whole run (decision, conditional upload with the 0.5/1.5/4 s + back-off, verified download, three-way merge, conflict copies and the three conflict choices, + then the baseline commit) behind `ISyncRemote`, `IVaultDocument` and the expanded `ICoreClient` + ports. The window keeps the WebDAV connection, the conflict dialog and the toast texts, which + shrank it by ~500 lines. Because the ordering rules are now outside WinUI, 38 headless + assertions pin them down: verify before replace, local write before upload, core baseline + commit before the sidecar says clean, 412 retries and the merge fallback, conflict-copy reuse + and dirty-on-failure. A clean sidecar is also cross-checked against the local file, so a crash + between the save and its baseline write cannot turn the next sync into a silent no-op. The FFI + wire DTOs moved to Core with the coordinator they describe, and the localization gate learned + the coordinator's status strings. +- **Sync baseline corruption is preserved:** an unreadable `state/*.json` sidecar is copied to `.corrupt-` before the vault is treated as dirty. `SyncStateStore` accepts an explicit directory for tests, and the headless suite covers round trip, missing-baseline clean state, malformed hash and corrupt-file preservation. +- **WebDAV downloads also reject redirects:** the download/metadata HTTP client no longer + follows redirects (the upload client already did not). A 3xx response fails the sync instead + of sending Basic credentials to the redirect target or replacing the working copy with a + different resource. The mock-server test asserts one request and a 302 error. +- **The application runs on .NET 10:** the shell targets `net10.0-windows10.0.19041.0`; Core, ViewModels, the app-core harness, FFI smoke test and maintenance drills target `net10.0`. Windows App SDK 1.8 and the existing packages build and run unchanged; self-contained publish, installer compilation and `--selftest` were verified on the installed .NET 10 runtime. CI/CodeQL/release use 10.0.x and `global.json` pins SDK 10.0.100 (`latestFeature`). +- **Conflict copies are written atomically:** both the local and remote conflict copies now go + through a flushed temporary file and atomic move (`AtomicFile.Copy` / `AtomicFile.Write`) + instead of a direct copy, so a crash cannot leave a truncated "conflict" file that a user + might later restore. +- **TOTP display is a view-model state machine:** `TotpDisplayViewModel` owns the selected entry, + generation guard, displayed code, countdown, window rollover and the three-second pre-fetch + (including adopting a pre-fetched code at the boundary). The shell passes a `TotpCodeSnapshot` + source and clock, keeps only the DispatcherTimer and maps the result to controls. Entry + switches cancel stale requests without showing the previous code. +- **Recent-database list is platform-neutral and corruption-safe:** `RecentDatabaseStore` moved + from the shell to `Keepassity.Core`, gained a testable explicit path, and preserves an + unreadable `recent-databases.json` as `.corrupt-` instead of silently discarding + it. Newest-first order, de-duplication, the five-entry cap and removal are covered headlessly. +- **Unreadable stored WebDAV credentials no longer break the UI:** a truncated or + wrong-user/machine DPAPI blob is moved to `.bin.corrupt-`, logged, and treated + as "no stored password" instead of throwing into settings or sync. The user can re-enter the + password and the corrupt bytes are kept for diagnosis. +- **Vault writes are serialized inside one process:** a `VaultWriteGate` now covers saves, + remote local-copy replacements and backup restores. Two async edit paths can no longer start + overlapping atomic replaces where a slower, older snapshot lands last; the first save keeps + its backup and the latest state wins. +- **Save temporary files use the core protocol name and are cleaned on unlock:** `AtomicFile` + now writes `.keepassity-tmp-` (the same infix as the core `save_atomic` + protocol) and removes crash-left siblings/legacy dot-prefixed temps before a vault opens. + Other databases' temps and the live file are never touched. +- **Backup files are created atomically:** the recovery copy is written to a flushed temporary + sibling and moved into place, so a crash mid-copy cannot leave a truncated file with a real + backup name. A name collision retries with the next suffix instead of overwriting. +- **Release artifacts are checksum-verified:** `SHA256SUMS` now includes the SBOM, uses LF + endings for `sha256sum -c` on any platform, and the release workflow recomputes every digest + before upload. The release gate also runs `fmt`, `clippy` and the public-file allowlist. +- **Settings can no longer be silently downgraded:** a settings file from a newer schema is + loaded but treated as read-only, so an older build cannot overwrite fields it does not + understand. An unreadable settings file is copied to `settings.json.corrupt-` + before defaults are used, preserving the evidence instead of destroying it. +- **TOTP countdown rules moved into a view model:** `TotpTiming` owns the remaining-second + clamp, 6/8-digit grouping, the "request a new code" decision, the three-second pre-fetch + window and the near-boundary timer interval. The shell keeps the timer and core calls; the + off-by-one window behavior now has headless tests. +- **Group navigation ordering moved into a projection:** `GroupNavigationProjection` now builds + the "All entries / normal groups / Templates / Recycle Bin" order outside the shell, with + counts and root/blank filtering, and is covered by headless tests. +- **Entry editor normalization moved into a view model:** `EntryEditorViewModel` owns the + untitled-entry fallback, trimmed fields, comma-separated tag parsing/deduplication and TOTP + defaults/clamping (SHA1/SHA256/SHA512, 6/8 digits, 1–300 s). Create and edit now use the same + rules; the "empty secret removes TOTP" decision is tested instead of living in two dialogs. +- **Detail panel state moved into the view model:** `EntryDetailViewModel` owns the title/group, + field visibility, tag formatting, custom-field selection and the password mask/reveal state; + the XAML detail panel binds the text and visibility through `x:Bind`. Password reveal no longer + writes UI controls directly, and the mask/divider rules now have headless tests. +- **Entry list presentation moved out of the shell:** row display logic (title/initial/avatar color, + username/URL/group fallback, TOTP badge), sorting, the TOTP filter and the row fingerprint now + live in `Keepassity.ViewModels` and run under the headless test harness. The shell keeps only a + thin `EntryRowPresenter` that turns the view model's color string and boolean into WinUI types; + the group navigation item is also a pure ViewModel type. +- **Uninstall no longer deletes user files:** the uninstaller used to remove the whole + installation directory (`filesandordirs {app}`), which would also delete a vault, backup or + note a user put next to the executable. Inno Setup now removes only the files it installed; + a directory containing user data is kept. A broken single-instance mutex is also logged and + ignored instead of crashing startup; the per-vault lock remains the writer guard. +- **Deleting a group is recoverable:** a group and everything inside it is moved to the Recycle + Bin (the whole subtree stays intact) instead of being permanently removed; when the Recycle + Bin is disabled the old tombstone-based permanent path is used. The confirmation dialog and + toast now say which happened. +- **Every save is verified before it can reach disk:** after serializing, the core decrypts and + parses the new ciphertext with the cached KDF key; `kp_save` and `kp_sync_merge` return an + error instead of bytes if the output is not a readable database. The check costs a decrypt, + not another KDF run, and the live file is only replaced after it succeeds. +- **Saving reuses the transformed KDF key:** after the first save of an unlocked vault, later + saves reuse the KDF salt and transformed key and only draw a fresh master seed, IV and + protected-stream key. The KDF cost/type and format version still match the source file, so the + compatibility guarantees are unchanged, but routine saves no longer spend hundreds of + milliseconds on Argon2/AES-KDF. The cache is dropped when the vault locks or closes. +- **One writer per vault, and no silent external overwrite:** opening a vault takes a cross-process + lock, so a second Keepassity window cannot save over the first. Before every save (and before a + remote download or merge replaces the local working copy) the app compares the file's SHA-256 + with the bytes its model was opened from; if another program changed the file, the save is + refused and the user is told to reopen, instead of overwriting their work. Settings, recent + databases, sync state and DPAPI credential files now use flushed, atomic writes too. +- **Saving keeps the KDBX 4 outer format:** the writer now carries the source version (4.0/4.1), + outer cipher, compression, KDF type and cost, and the `PublicCustomData` header field through a + save. A KDBX 4.1 vault is no longer downgraded to 4.0, and an AES-KDF vault is no longer + silently rewritten with the writer's Argon2id defaults. KDBX 3.1 sources still follow the + documented upgrade to KDBX 4.0. This also makes the core's verified rewrite path accept the + model writer's output. +- **Durable saves and deletes:** the save path now writes a flushed sibling temporary file, keeps the + previous database as a timestamped backup, and replaces the live file atomically; failed or + interrupted saves leave either the old or the new database, never a partial file. Deleting an + entry now creates the Recycle Bin group when the database enables recycling but has no usable + group UUID, so a new database no longer silently turns a delete into an unrecoverable tombstone + while the UI promises a recycle bin. +- **Settings is now an MVVM panel:** the Settings/About page is a bound `SettingsPanel` + backed by `SettingsViewModel`; appearance, language, clipboard, auto-lock, backup retention + and sync-on-save still apply immediately, while the WebDAV source is committed on Save. + Stored-credential state, HTTPS validation, DPAPI storage, diagnostics export and the + About/license text moved out of the window code-behind without changing the user-visible + flow. +- **Sync and restore fail closed:** a WebDAV upload that receives a redirect (for example a 303) + is rejected instead of being replayed as a body-less GET whose 200 response looked like a + successful database upload; non-loopback plain HTTP is refused because Basic authentication + would expose the WebDAV password. Remote bytes applied to an unlocked vault are decrypted + with the current master password before the local database is replaced, a corrupt sync + sidecar is treated as dirty instead of clean, and a sync baseline without a content hash is + rejected. Backups are ordered by their creation name rather than the copied file's timestamp, + are flushed before use, and an empty restore payload is rejected. +- **Password generator page:** Generate in the entry form now opens the generator in the right pane + instead of a flyout, so the result, entropy, hint, options and actions use the full column. Back + returns to the form with everything already typed; Done returns to the form with the generated + password in the field, and Save stores the entry. The generated password is shown in a read-only + preview with a Copy button, and changing an option regenerates immediately. This also removes the + old flyout's clipping: the page cannot flip above the field or hide its buttons. +- **Detail pane refreshes after a password-only edit:** saving an entry whose visible list fields did + not change (for example right after using the password generator) used to leave the detail pane on + the previous entry content, so revealing or copying the password returned the old secret until + another entry was selected and reselected. The save now refreshes the selected entry's detail even + when the middle column keeps its rows, and that refresh does not replay the entry animation. +- **Saving keeps the vault metadata:** a save now writes back the fields the reader parses but the + writer used to drop — entry and group icons (built-in and custom icon references), entry colors, + override URLs, Auto-Type settings, custom data, group notes and auto-type/search flags, the meta + memory-protection, default-user-name, custom-data and custom-icon elements, per-field protection + and the recycle-bin timestamp. The merge compares semantic content (ignoring field order, tag + order, empty fields, protection flags and unknown XML) and treats a side that lost optional + metadata as the same content, so a vault saved by an earlier build no longer produces conflict + dialogs for entries that were never edited, and an unresolved conflict keeps its single local / + remote copy pair instead of writing another one on every sync attempt. Compatibility: the saved + file stays KDBX 4.0, upgraded to 4.1 only when a custom icon carries a name or modification time; + files written by other KeePass clients remain readable and mergeable. +- **Product-name casing:** product text in the app UI, the installer/Apps & Features display + name and the `.kdbx` file-association label now read **Keepassity**. File and folder names, + environment variables, the AUMID/ProgID and URLs keep the lowercase `keepassity` spelling. + The localization gate rejects a lowercase product name in a UI catalog key or translation, so + the convention cannot silently regress. +- **Smooth navigation pane toggle:** collapsing or expanding the navigation pane resizes the + workspace columns frame by frame instead of snapping them to their final width while only + the pane slides. The pane length is animated in layout (200 ms opening, 180 ms closing, + eased out), the compact icon rail is unchanged, and the system "show animations" setting + falls back to the plain toggle. This removes the visible jump between the pane and the + entry list / detail columns. +- **UI language switch (English / Simplified Chinese):** the Windows shell is now localized. + Settings (and the unlock page) offer "use the system language", English and 简体中文; the + choice is persisted in `settings.json` and applies immediately without restarting or + re-unlocking — XAML labels, code-built panels, dialogs, toasts, tooltips, accessibility + names and the tray menu all follow the selected language. Translations are embedded JSON + catalogs (`Keepassity.Core/Localization/*.zh-CN.json`) keyed by the English source text, so + an untranslated string falls back to readable English. New gates: `tools/check-localization.ps1` + and catalog tests in `tests/app-core` (see `docs/testing.md`). +- **Entries can leave a folder again:** the virtual "All entries" row is a drop target that moves + an entry to the vault root, and the Move dialog offers `Top level (no folder)`. Dropping an + entry on the group (or top level) it already lives in is refused with a hint instead of a + pointless save and a row that disappears until the next reload. - **WebDAV 412 back-off retry (SY-08):** when the remote file changes while an upload is being prepared (HTTP 412), the app now retries three times with the same 0.5 s / 1.5 s / 4 s back-off schedule as the core sync state machine, then resolves the change through the three-way merge/conflict path - the remote is never overwritten silently. - **WebDAV server presets and app-password guidance:** the Open-from-WebDAV dialog offers URL presets for Nextcloud/ownCloud, Synology WebDAV and Jianguoyun, and every WebDAV entry point (open, new database, settings, sync) refuses plain `http://` URLs and reminds two-factor accounts to use an app password. - **WebDAV TLS and self-signed certificates:** WebDAV URLs now require `https://` (Basic @@ -24,13 +385,12 @@ KDBX write-path changes must state the compatibility impact. WebDAV merge reloads the database: unchanged lists are no longer re-rendered, and moved rows are updated in place when they stay visible. -The `v1.0.0` tag and GitHub Release are created only after the 30-day acceptance passes; see -`docs/release.md`. +The `v1.0.0` tag and GitHub Release were published on 2026-12-01; see `docs/release.md`. -## [1.0.0] - 2026-11-09 +## [1.0.0-rc.1] - 2026-11-09 -First v1.0.0 build. The source tree is at version 1.0.0; the tag and GitHub Release are -pending the 30-day real-use acceptance described in `docs/release.md`. +First v1.0.0 release-candidate build. The source tree was at version 1.0.0; no tag was created +for this build. ### Added @@ -139,9 +499,8 @@ English UI. The full matrix, including untested states, is in `docs/compatibilit - The binaries are unsigned, so Windows SmartScreen may warn; releases ship with SHA-256 checksums and build-provenance attestations only (no code signing, no MSIX, no auto-update). -- `v1.0.0` is not published yet: the 30-day acceptance runs first, then the tag/release is - created. No GitHub Release exists today; the obsolete `v0.1.0` draft and tag were removed - on 2026-11-09 (see `docs/release.md`). +- `v1.0.0` was published on 2026-12-01. The obsolete `v0.1.0` draft and tag were removed on + 2026-11-09 (see `docs/release.md`). - Windows 11 x64 only; Linux is planned for v1.x. ## [0.1.0] - 2026-10-28 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fde1370..5bd762d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,14 +10,11 @@ contain secrets. - **Rust:** pinned by `rust-toolchain.toml` to **1.99.1** (the same version CI uses, together with `rustfmt` and `clippy`). Update the pin and CI in the same change. -- **.NET SDK:** CI installs **8.0.x**. `global.json` pins SDK `8.0.100` with - `rollForward: latestMajor`, so a newer local SDK is used automatically. The maintainer's - machine-wide SDK installation (currently 10.0.402) is partially broken (missing workload - resolvers), so local builds use a user-local `dotnet-install` copy in `%USERPROFILE%\.dotnet` - that `scripts\test.ps1` prefers, and the shell is built **project-level** from the - checked-in files. Do not scaffold or regenerate the app with `dotnet new`/WinUI templates; - if your local SDK cannot build the checked-in solution, install the 8.0.x SDK and let - `global.json` select it. +- **.NET SDK:** CI installs **10.0.x**. `global.json` pins SDK `10.0.100` with + `rollForward: latestFeature`, so a newer local 10.0.x SDK is used automatically. The shell is + built **project-level** from the checked-in files; do not scaffold or regenerate the app with + `dotnet new`/WinUI templates. If your local SDK cannot build the checked-in solution, install + the 10.0.x SDK and let `global.json` select it. - **Windows App SDK / IDE:** Visual Studio with the Windows App SDK C# templates (WinUI 3 shell); the target project is `apps/windows/Keepassity.sln`. - **Native FFI library** must be built first: @@ -43,13 +40,19 @@ contain secrets. -D warnings`, `cargo test --workspace`, the fixture manifest check, the Windows build and the headless service tests. You can also run the individual commands from the README ("Build from source" / "Testing"). -4. The UI is English-only: run `powershell -NoProfile -ExecutionPolicy Bypass -File - tools\check-ui-strings.ps1` if you touch `apps/windows/` (it rejects hard-coded CJK text; - see `docs/testing.md`). -5. Run `powershell -NoProfile -ExecutionPolicy Bypass -File scripts\check-public.ps1` before +4. UI text lives in the language catalogs: run `powershell -NoProfile -ExecutionPolicy Bypass + -File tools\check-ui-strings.ps1` and `... -File tools\check-localization.ps1 -Strict` if + you touch `apps/windows/` (no hard-coded CJK; every `Loc.T`/XAML key has a translation; see + `docs/testing.md`). +5. Product-name casing: UI text (window title, About, tray menu, notifications, installer and + file-association labels) spells the product **Keepassity**. The lowercase `keepassity` + spelling is reserved for file/folder names, environment variables, identifiers (AUMID, + ProgID) and URLs. `tools/check-localization.ps1` fails on a lowercase product name in a UI + catalog key or translation. +6. Run `powershell -NoProfile -ExecutionPolicy Bypass -File scripts\check-public.ps1` before pushing. It enforces `public.allowlist`; real vaults and credentials never enter this repository. -6. AI-generated code is fine, but the human submitting the PR is responsible for verifying +7. AI-generated code is fine, but the human submitting the PR is responsible for verifying behavior — say in the PR what you verified manually. ## Public repository boundary diff --git a/Directory.Build.props b/Directory.Build.props index 82582e0..eb9b880 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -11,6 +11,12 @@ true true true + + false $(MSBuildProjectDirectory)\packages.lock.json diff --git a/Directory.Packages.props b/Directory.Packages.props index 1c0d938..b141229 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -3,6 +3,7 @@ true + diff --git a/README.md b/README.md index e00eece..0a194bb 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ A Windows-first, open-source password manager for KeePass **KDBX** databases, wi ## Status -**v1.0.0 (release pending acceptance).** The Windows app covers the v1.0 scope: it opens +**v1.0.0 (released 2026-12-01).** The Windows app covers the v1.0 scope: it opens local files or databases served over WebDAV, unlocks, browses, edits, moves and saves entries and groups, shows and edits TOTP codes (including QR / `otpauth` import and next-window prefetch), keeps timestamped local backups with restore, and syncs over WebDAV with explicit @@ -21,8 +21,8 @@ the manual G3/G4 gates (main flows, real Jianguoyun sync, install/uninstall) wer on 2026-11-08/09, and the app has been used against a real KeePass 2.x database (G0, 2026-10-25: round trip, KeePass 2.x reopen, 10-entry spot-check including 3 TOTP codes). -v1.0.0 is **not published yet**: the 1.0.0 build goes through a 30-day real-use acceptance -before the `v1.0.0` tag and GitHub Release are created. No GitHub Release has been published. +The `v1.0.0` release is published on GitHub (2026-12-01) with the portable zip and the +per-user installer. The binaries are unsigned (SmartScreen warning), and there is no MSIX packaging or auto-update. Key file / challenge-response credentials and Windows Hello are out of scope for v1.0, and there is no attachments/history/recycle-bin management UI (the data itself is @@ -48,9 +48,10 @@ preserved). The v1.0 scope is frozen by the maintainer. - **Security:** auto-lock after inactivity and on Windows session lock/logoff/suspend, clipboard secrets cleared after 30 seconds and marked not to enter Win+V / cloud clipboard history, WebDAV passwords stored with Windows DPAPI. -- **Shell:** English WinUI 3 UI with system/light/dark theme, search, sorting and filtering, - entry/group drag-and-drop, tray menu (show / lock / exit), single-instance behaviour, - inline settings panel and `--selftest` mode. +- **Shell:** WinUI 3 UI with **English and Simplified Chinese** (switchable at runtime in + Settings or on the unlock page, plus "use the system language"), system/light/dark theme, + search, sorting and filtering, entry/group drag-and-drop, tray menu (show / lock / exit), + single-instance behaviour, inline settings panel and `--selftest` mode. - **Windows integration:** the installer is per-user (no administrator rights), installs under `%LOCALAPPDATA%\Programs\keepassity` with Start menu / desktop shortcuts and an uninstaller that keeps user data, and registers a per-user candidate `.kdbx` association @@ -72,9 +73,8 @@ draft contains: Build provenance attestations for the artifacts are generated by the same workflow (`actions/attest-build-provenance`). -No GitHub Release has been published yet. The current build is `v1.0.0`, which goes through a -30-day real-use acceptance before the tag and release are created. Until then, build the -portable folder from source (below). +The latest release is `v1.0.0` (2026-12-01), available from the GitHub Releases page. You can +also build the portable folder from source (below). Once a release is published: @@ -113,8 +113,8 @@ your PC" / "Unknown publisher". Verify the SHA-256 checksum first, then choose v1.0 is a Windows-first, single-database client for KeePass KDBX databases with native WebDAV sync and built-in TOTP (see **Features** above), shipped as a portable folder and a -per-user Inno Setup installer for Windows 11 x64. The `v1.0.0` tag and release are created -after the 30-day acceptance period passes (see `docs/release.md`). +per-user Inno Setup installer for Windows 11 x64. The `v1.0.0` tag and release were published +on 2026-12-01 (see `docs/release.md`). Not in v1.0: browser extension, auto-type, Windows Hello, attachments/history/recycle-bin management UI, multi-database, mobile, macOS, Linux (Linux is planned for v1.x). @@ -126,7 +126,7 @@ management UI, multi-database, mobile, macOS, Linux (Linux is planned for v1.x). | `crates/core` | Rust core: KDBX parsing/writing, crypto, merge/sync decisions, TOTP (no IO, no network) | | `crates/ffi` | C ABI + JSON bridge | | `crates/cli` | CLI harness for CI, interop and acceptance checks (not shipped with the app) | -| `apps/windows` | WinUI 3 shell (`Keepassity.Mock`); talks to the core through the FFI v1 C ABI | +| `apps/windows` | WinUI 3 shell (`Keepassity.App`); talks to the core through the FFI v1 C ABI | | `tests/fixtures` | Public KDBX test corpus (MIT, from keepass-rs) plus a generated 500-entry synthetic database | | `tools/interop` | Test-only interop verification harness (KeePassLib + keepassxc-cli) | | `docs/` | Architecture, compatibility, testing and release notes | @@ -134,9 +134,9 @@ management UI, multi-database, mobile, macOS, Linux (Linux is planned for v1.x). ## Build from source Toolchain: Rust stable, pinned in `rust-toolchain.toml`; for the Windows shell, .NET SDK -8.0 or newer and the Windows App SDK. `global.json` pins SDK 8.0.100 with -`rollForward: latestMajor`, so a newer installed SDK (for example 10.0.402) is used -automatically; CI installs 8.0.x. Inno Setup 6 is needed only to build the installer. +10.0.x and the Windows App SDK. `global.json` pins SDK 10.0.100 with +`rollForward: latestFeature`, so a newer installed 10.0.x SDK is used automatically; CI +installs 10.0.x. Inno Setup 6 is needed only to build the installer. Core and interop checks (no UI needed): @@ -154,7 +154,7 @@ powershell -NoProfile -ExecutionPolicy Bypass -File scripts\publish-windows.ps1 ``` For IDE work, open `apps/windows/Keepassity.sln` in Visual Studio 2026 (or the -`Keepassity.Mock.csproj` directly); `apps/windows/.vsconfig` lists the required IDE +`Keepassity.App.csproj` directly); `apps/windows/.vsconfig` lists the required IDE components (Windows App SDK C#, Windows 11 SDK, .NET desktop workload). Build `keepassity-ffi` in release mode once first, because the app copies the native `keepassity_ffi.dll` next to its output and cannot open a database without it. diff --git a/THIRD-PARTY-LICENSES.md b/THIRD-PARTY-LICENSES.md index e20f990..a7bd7a6 100644 --- a/THIRD-PARTY-LICENSES.md +++ b/THIRD-PARTY-LICENSES.md @@ -2,7 +2,7 @@ > Every dependency listed here must be verifiable with `cargo deny` or the package's license > file. Direct NuGet dependencies are pinned in `Directory.Packages.props`; resolved versions -> (including transitives) are recorded in `apps/windows/Keepassity.Mock/packages.lock.json` +> (including transitives) are recorded in `apps/windows/Keepassity.App/packages.lock.json` > and `tests/*/packages.lock.json`. | Component | Version | License | Usage | Notes | diff --git a/apps/windows/Keepassity.App/AboutPanel.xaml b/apps/windows/Keepassity.App/AboutPanel.xaml new file mode 100644 index 0000000..8ed3a5a --- /dev/null +++ b/apps/windows/Keepassity.App/AboutPanel.xaml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + - - - + loc:LocMarkup.Name="Unlocking database" /> - + @@ -254,12 +263,12 @@ HorizontalAlignment="Stretch" HorizontalContentAlignment="Left" MinHeight="36" - AutomationProperties.Name="Open local database file" + loc:LocMarkup.Name="Open local database file" AutomationProperties.AutomationId="OpenLocalDatabaseButton" Click="ChooseDatabaseButton_Click"> - + - + + + + + + + + + + + + + + @@ -305,7 +360,7 @@ IsSettingsVisible="False" OpenPaneLength="232" Background="Transparent" - AutomationProperties.Name="Database navigation" + loc:LocMarkup.Name="Database navigation" AutomationProperties.AutomationId="MainNavigation" SelectionChanged="NavView_SelectionChanged" ItemInvoked="NavView_ItemInvoked"> @@ -324,33 +379,34 @@ - - - + loc:LocMarkup.HelpText="Locks the vault immediately (Ctrl+L)"> - @@ -364,11 +420,15 @@ of two independently positioned overlays. --> + and bottom are square and sit on the window edge. The top + and left hairlines wrap the rounded corner (the same + 1,1,0,0 frame NavigationView draws for its content grid); + with only the top side stroked the corner would end in a + dangling hook and the pane/content seam would have no line. --> + BorderBrush="{ThemeResource HairlineBrush}" + BorderThickness="1,1,0,0"> @@ -378,7 +438,7 @@ @@ -402,8 +462,8 @@ VerticalAlignment="Center"> @@ -444,7 +505,7 @@ - + @@ -488,7 +549,7 @@ Spacing="8" Visibility="Collapsed"> - @@ -511,29 +572,29 @@ - - @@ -543,100 +604,100 @@ - - + - + + Text="{x:Bind Detail.Username, Mode=OneWay}" Style="{StaticResource FieldValue}" /> - - + + - + - - + + - + + Text="{x:Bind Detail.Url, Mode=OneWay}" Style="{StaticResource FieldValue}" /> - - + + - + @@ -657,12 +718,12 @@ - + @@ -691,30 +752,30 @@ - - - + - - @@ -723,17 +784,17 @@ - - - + + Text="{x:Bind Detail.Notes, Mode=OneWay}" /> @@ -751,7 +812,7 @@ @@ -762,7 +823,7 @@ rather than removed from the tree. --> diff --git a/apps/windows/Keepassity.App/MainWindow.xaml.cs b/apps/windows/Keepassity.App/MainWindow.xaml.cs new file mode 100644 index 0000000..d7318ed --- /dev/null +++ b/apps/windows/Keepassity.App/MainWindow.xaml.cs @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Microsoft.UI.Windowing; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Automation; +using Microsoft.UI.Xaml.Automation.Peers; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Controls.Primitives; +using Microsoft.UI.Xaml.Input; +using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.Media.Animation; +using Microsoft.UI.Xaml.Media.Imaging; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Net.NetworkInformation; +using System.Reflection; +using System.Runtime.InteropServices; +using Windows.ApplicationModel.DataTransfer; +using Windows.Graphics; +using Windows.Storage; +using Windows.Storage.Pickers; +using Windows.Storage.Streams; +using Windows.System; +using Windows.UI; +using Windows.UI.ViewManagement; +using Keepassity.ViewModels; + +namespace Keepassity.App; + +public sealed partial class MainWindow : Window +{ + public ObservableCollection Groups { get; } = new(); + public ObservableCollection Entries { get; } = new(); + + /// State and display strings for the unlock surface (MVVM boundary). + public UnlockViewModel Unlock { get; } + + /// State and display strings for the detail panel (MVVM boundary). + public EntryDetailViewModel Detail { get; } + + /// TOTP display state machine (MVVM boundary). + public TotpDisplayViewModel Totp { get; } + + /// Localized sync status shown in the navigation pane. + public SyncStatusViewModel SyncStatus { get; } + + private readonly CoreClient _core = new(); + private readonly AppSettingsStore _settingsStore = new(); + private readonly UISettings _uiSettings = new(); + private readonly SyncStateStore _syncStates = new(); + private readonly CredentialStore _credentials = new(); + private readonly SemaphoreSlim _syncGate = new(1, 1); + // The sync protocol (decision, back-off, verification, conflict rules and + // baseline ordering) lives in Core; the window supplies the open vault, the + // WebDAV client and the conflict dialog. + private readonly SyncCoordinator _sync; + // A WebDAV download is held here until the master password opens its bytes; + // only then is the working copy replaced (see RemoteVaultOpener). + private readonly RemoteVaultOpener _remoteOpener; + private readonly NewDatabasePreparer _newDatabase; + private readonly RunStateStore _runState = new(); + private PendingRemoteDatabase? _pendingRemoteDownload; + private PreviousRun? _previousRun; + private bool _repairUnreadableRemoteOnce; + private string? _corruptRecoveryPath; + private bool _corruptRecoveryOffered; + private readonly DispatcherTimer _totpTimer = new(); + private readonly DispatcherTimer _toastTimer = new(); + private readonly DispatcherTimer _autoLockTimer = new(); + private readonly DispatcherTimer _clipboardTimer = new(); + private readonly List _groupDtos = new(); + private readonly List _selectableGroups = new(); + private readonly Dictionary _groupNames = new(); + + private string? _dbPath; + private bool _webDavSource; + private string? _sourceWebDavUrl; + private readonly VaultProfileStore _profiles = new(); + private VaultProfile? _profile; + private string? _selectedGroupUuid; + private string? _recycleBinGroupUuid; + private string? _rootGroupUuid; + private EntryFullDto? _currentFull; + private EntryRowPresenter? _currentSummary; + private string? _lastClipboardText; + private string? _masterPassword; + private readonly VaultSession _vault = new(); +} diff --git a/apps/windows/Keepassity.Mock/QrDecoder.cs b/apps/windows/Keepassity.App/QrDecoder.cs similarity index 98% rename from apps/windows/Keepassity.Mock/QrDecoder.cs rename to apps/windows/Keepassity.App/QrDecoder.cs index 81a7807..a436e97 100644 --- a/apps/windows/Keepassity.Mock/QrDecoder.cs +++ b/apps/windows/Keepassity.App/QrDecoder.cs @@ -6,7 +6,7 @@ using ZXing; using ZXing.Common; -namespace Keepassity.Mock; +namespace Keepassity.App; /// Decodes an otpauth QR image or a clipboard screenshot in the UI layer. public static class QrDecoder diff --git a/apps/windows/Keepassity.Mock/README.md b/apps/windows/Keepassity.App/README.md similarity index 84% rename from apps/windows/Keepassity.Mock/README.md rename to apps/windows/Keepassity.App/README.md index 463c5bb..e206bec 100644 --- a/apps/windows/Keepassity.Mock/README.md +++ b/apps/windows/Keepassity.App/README.md @@ -10,7 +10,7 @@ The shell requires the native FFI DLL: ```powershell cargo build -p keepassity-ffi --release -dotnet build apps/windows/Keepassity.Mock/Keepassity.Mock.csproj -c Debug +dotnet build apps/windows/Keepassity.App/Keepassity.App.csproj -c Debug ``` The project copies `target/release/keepassity_ffi.dll` next to the app on build @@ -20,7 +20,7 @@ included in the output). ## Run ```powershell -apps/windows/Keepassity.Mock/bin/Debug/net8.0-windows10.0.19041.0/win-x64/Keepassity.exe +apps/windows/Keepassity.App/bin/Debug/net10.0-windows10.0.19041.0/win-x64/Keepassity.exe ``` 1. Choose a `.kdbx` file, or use **New database…** to create an empty KDBX 4.0 @@ -30,8 +30,10 @@ apps/windows/Keepassity.Mock/bin/Debug/net8.0-windows10.0.19041.0/win-x64/Keepas 4. `Edit TOTP` sets/removes TOTP; import from a QR image or clipboard otpauth URI, or paste a Base32 secret manually. `Copy` works on passwords and codes. 5. Changes are saved atomically to the same `.kdbx`; a timestamped backup is - copied to `.keepassity\backups\\` before every save. Lock saves and closes - the handle. + copied to `.keepassity\backups\\` before every save. Opening a writable + database folder also takes `.keepassity\locks\.lock`, so another Windows + account or machine opening the same shared folder is refused instead of + writing over it. Lock saves and closes the handle. `--db ` pre-fills the database, and a bare `.kdbx` path (file association / "Open with") is handed to the running instance. The diagnostic overrides are @@ -85,9 +87,14 @@ non-zero on failure. The report contains counts/status only, never secrets. Show / Lock / Exit, and closing the window hides it to the tray with a one-time hint. An optional setting starts the app minimized; `--no-tray` is a test-only bypass. -- Settings persisted to `%LOCALAPPDATA%\keepassity\settings.json`: theme, clipboard - clearing, auto-lock enable/minutes, backup retention, window bounds, start +- Settings persisted to `%LOCALAPPDATA%\keepassity\settings.json`: theme, UI language, + clipboard clearing, auto-lock enable/minutes, backup retention, window bounds, start minimized, and the last opened database path. +- **UI language**: English and Simplified Chinese, switchable at runtime in Settings or on + the unlock page (plus "use the system language"), applied without restarting and persisted + in `settings.json`. English source strings are the catalog keys; translations live in + `Keepassity.Core/Localization/*.zh-CN.json` (see `docs/testing.md`, UI strings). The tray + menu, tooltips, dialogs, toasts and the About/GPL section follow the selected language. - Clipboard secrets are cleared after 30 seconds if they are still the current clipboard text, and are marked not to enter Win+V history or cloud clipboard (`ClipboardContentOptions`). @@ -118,7 +125,7 @@ non-zero on failure. The report contains counts/status only, never secrets. ## Notes -- The project is still named `Keepassity.Mock` because it began as the UI prototype; - the UI is the intended shell and now talks to the real core. +- The project is `Keepassity.App` (renamed from the original `Keepassity.Mock` + prototype in the v1.1 line) and ships `Keepassity.exe`. - Fixture passwords are public test values from `tests/fixtures`; no real vault is committed. `.spike/` and `docs/spike/` are local review artifacts only. diff --git a/apps/windows/Keepassity.Mock/SessionLockMonitor.cs b/apps/windows/Keepassity.App/SessionLockMonitor.cs similarity index 99% rename from apps/windows/Keepassity.Mock/SessionLockMonitor.cs rename to apps/windows/Keepassity.App/SessionLockMonitor.cs index 082910b..9ce6d7e 100644 --- a/apps/windows/Keepassity.Mock/SessionLockMonitor.cs +++ b/apps/windows/Keepassity.App/SessionLockMonitor.cs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later using System.Runtime.InteropServices; -namespace Keepassity.Mock; +namespace Keepassity.App; /// /// Watches the main window for the Windows session/power messages that must diff --git a/apps/windows/Keepassity.App/SettingsPage.xaml b/apps/windows/Keepassity.App/SettingsPage.xaml new file mode 100644 index 0000000..f280e16 --- /dev/null +++ b/apps/windows/Keepassity.App/SettingsPage.xaml @@ -0,0 +1,99 @@ + + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/windows/Keepassity.App/SettingsPage.xaml.cs b/apps/windows/Keepassity.App/SettingsPage.xaml.cs new file mode 100644 index 0000000..5d31d4f --- /dev/null +++ b/apps/windows/Keepassity.App/SettingsPage.xaml.cs @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; + +namespace Keepassity.App; + +/// Which owner the settings page is showing. +public enum SettingsScope +{ + /// Settings stored in the application settings file: every database. + Application = 0, + + /// Settings stored in or next to the open database file. + Database = 1, +} + +/// +/// The settings place: one fixed page header and a two-item scope switch (a +/// WinUI ) whose tabs own the application settings and the +/// open database's settings. Each tab scrolls on its own, so switching scopes +/// never carries the other tab's offset along. +/// +/// The panels are built by the shell because they need the view models; the page +/// only places them and decides whether the database scope exists at all. Without +/// an open database the database tab is removed instead of being shown disabled: +/// there is no object, so there is nothing to configure. +/// +public sealed partial class SettingsPage : UserControl +{ + private readonly bool _hasDatabase; + + /// Raised when the reader picks the other scope. + public event Action? ScopeChanged; + + /// The application-wide settings panel. + /// The open database panel, or null when locked. + /// The version, licence and diagnostics panel. + /// Scope to select when the page is built. + public SettingsPage(UIElement application, UIElement? database, UIElement about, + SettingsScope initialScope) + { + InitializeComponent(); + ApplicationHost.Children.Add(application); + AboutHost.Children.Add(about); + _hasDatabase = database is not null; + if (database is null) + { + // No database: remove the whole scope item, not just its content, so + // neither a grey tab nor an empty page can suggest there is something + // to configure. + ScopePivot.Items.Remove(DatabasePivotItem); + ScopePivot.SelectedItem = ApplicationPivotItem; + } + else + { + DatabaseHost.Children.Add(database); + ScopePivot.SelectedItem = initialScope == SettingsScope.Database + ? DatabasePivotItem + : ApplicationPivotItem; + } + } + + /// The scope the reader is looking at now. + public SettingsScope CurrentScope => + _hasDatabase && ReferenceEquals(ScopePivot.SelectedItem, DatabasePivotItem) + ? SettingsScope.Database + : SettingsScope.Application; + + private void ScopePivot_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + // Remembering the scope is the host's job; the page reports every change + // and does not reset the content, because both panels were built once. + if (_hasDatabase) + { + ScopeChanged?.Invoke(CurrentScope); + } + } +} diff --git a/apps/windows/Keepassity.App/SettingsPanel.xaml b/apps/windows/Keepassity.App/SettingsPanel.xaml new file mode 100644 index 0000000..a547c31 --- /dev/null +++ b/apps/windows/Keepassity.App/SettingsPanel.xaml @@ -0,0 +1,155 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/windows/Keepassity.App/SettingsPanel.xaml.cs b/apps/windows/Keepassity.App/SettingsPanel.xaml.cs new file mode 100644 index 0000000..cd6fc2b --- /dev/null +++ b/apps/windows/Keepassity.App/SettingsPanel.xaml.cs @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.ViewModels; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; + +namespace Keepassity.App; + +/// +/// View for : appearance, language and behaviour, +/// laid out as grouped cards so every row follows the same pattern (name and +/// explanation on the left, the control on the right). Labels are view concerns; +/// data and decisions stay in the view model. +/// +public sealed partial class SettingsPanel : UserControl +{ + public SettingsPanel(SettingsViewModel viewModel) + { + ViewModel = viewModel; + InitializeComponent(); + ThemeCombo.Items.Add(Loc.T("Use system setting")); + ThemeCombo.Items.Add(Loc.T("Light")); + ThemeCombo.Items.Add(Loc.T("Dark")); + ThemeCombo.SelectedIndex = viewModel.ThemeIndex; + LanguageCombo.ItemsSource = viewModel.Languages; + LanguageCombo.DisplayMemberPath = nameof(LanguageOption.DisplayName); + LanguageCombo.SelectedValuePath = nameof(LanguageOption.Setting); + LanguageCombo.SelectedValue = viewModel.SelectedLanguage; + ClipboardToggle.OnContent = Loc.T("On"); + ClipboardToggle.OffContent = Loc.T("Off"); + AutoLockToggle.OnContent = Loc.T("On"); + AutoLockToggle.OffContent = Loc.T("Off"); + StartMinimizedToggle.OnContent = Loc.T("On"); + StartMinimizedToggle.OffContent = Loc.T("Off"); + } + + public SettingsViewModel ViewModel { get; } + + private void ThemeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + if (ThemeCombo.SelectedIndex >= 0) + { + ViewModel.ThemeIndex = ThemeCombo.SelectedIndex; + } + } + + private void LanguageCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + if (LanguageCombo.SelectedItem is LanguageOption option && + !string.Equals(option.Setting, ViewModel.SelectedLanguage, + StringComparison.OrdinalIgnoreCase)) + { + ViewModel.SelectedLanguage = option.Setting; + } + } +} diff --git a/apps/windows/Keepassity.App/SingleInstanceRelay.Forward.cs b/apps/windows/Keepassity.App/SingleInstanceRelay.Forward.cs new file mode 100644 index 0000000..b02dc99 --- /dev/null +++ b/apps/windows/Keepassity.App/SingleInstanceRelay.Forward.cs @@ -0,0 +1,164 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; + +namespace Keepassity.App; + +internal sealed partial class SingleInstanceRelay : IDisposable +{ + + /// + /// Sends an open request to the running instance for the same executable. + /// Returns true only when the request was delivered and accepted. + /// + internal static bool TryForward(string databasePath, out string outcome) + { + outcome = "not sent"; + if (!TryNormalizeDatabasePath(databasePath, out string fullPath)) + { + outcome = "the database path is invalid"; + return false; + } + IntPtr target = FindWindow(null, RelayWindowTitle); + if (target == IntPtr.Zero) + { + outcome = "no running instance answered"; + return false; + } + _ = GetWindowThreadProcessId(target, out uint targetProcessId); + if (targetProcessId == 0 || targetProcessId == (uint)Environment.ProcessId) + { + outcome = "the relay window has an unexpected owner"; + return false; + } + if (!IsSameApplication(targetProcessId)) + { + outcome = "the relay window belongs to another application"; + return false; + } + byte[]? payload = EncodePath(fullPath); + if (payload is null) + { + outcome = "the database path is too long"; + return false; + } + IntPtr buffer = Marshal.AllocHGlobal(payload.Length); + IntPtr senderWindow = IntPtr.Zero; + try + { + Marshal.Copy(payload, 0, buffer, payload.Length); + // WM_COPYDATA expects wParam to identify a window owned by the + // sending process. A hidden STATIC window is enough for that; the + // receiver only uses it to check the sender process. + senderWindow = CreateWindowEx(WsExToolWindow, "STATIC", + "kdbx-open-sender", WsPopup, 0, 0, 0, 0, + IntPtr.Zero, IntPtr.Zero, GetModuleHandle(null), IntPtr.Zero); + if (senderWindow == IntPtr.Zero) + { + outcome = "the sender window could not be created"; + return false; + } + var data = new CopyDataStruct + { + Signature = new IntPtr(Magic), + Size = payload.Length, + Data = buffer, + }; + IntPtr structPointer = Marshal.AllocHGlobal(Marshal.SizeOf()); + try + { + Marshal.StructureToPtr(data, structPointer, false); + IntPtr sent = SendMessageTimeout(target, WmCopyData, senderWindow, + structPointer, SmtoBlock | SmtoAbortIfHung, SendTimeoutMilliseconds, + out IntPtr messageResult); + if (sent == IntPtr.Zero) + { + outcome = $"the receiver did not answer (error {Marshal.GetLastPInvokeError()})"; + return false; + } + if (messageResult == IntPtr.Zero) + { + outcome = "the running instance rejected the request"; + return false; + } + outcome = "the running instance received the path"; + return true; + } + finally + { + Marshal.FreeHGlobal(structPointer); + } + } + finally + { + if (senderWindow != IntPtr.Zero) + { + _ = DestroyWindow(senderWindow); + } + Marshal.FreeHGlobal(buffer); + } + } + + /// Encodes a path as UTF-16LE bytes, or null when it is unusable. + internal static byte[]? EncodePath(string path) + { + if (string.IsNullOrWhiteSpace(path)) + { + return null; + } + string fullPath; + try + { + fullPath = Path.GetFullPath(path); + } + catch + { + return null; + } + if (fullPath.Length > MaxPathCharacters) + { + return null; + } + byte[] payload = Encoding.Unicode.GetBytes(fullPath); + return payload.Length is > 0 and <= MaxPayloadBytes ? payload : null; + } + + /// Decodes a UTF-16LE payload, or null when it is malformed. + internal static string? DecodePath(ReadOnlySpan payload) + { + if (payload.Length == 0 || payload.Length > MaxPayloadBytes || + payload.Length % 2 != 0) + { + return null; + } + string decoded = Encoding.Unicode.GetString(payload); + return decoded.IndexOf('\0') >= 0 ? null : decoded; + } + + /// + /// Validates a candidate path for the open hand-off: absolute path, at most + /// the Windows path limit, an existing .kdbx file. + /// + internal static bool TryNormalizeDatabasePath(string? candidate, out string fullPath) + { + fullPath = string.Empty; + if (string.IsNullOrWhiteSpace(candidate) || + candidate.Length > MaxPathCharacters || + candidate.IndexOf('\0') >= 0) + { + return false; + } + try + { + fullPath = Path.GetFullPath(candidate); + } + catch + { + return false; + } + return fullPath.EndsWith(".kdbx", StringComparison.OrdinalIgnoreCase) && + File.Exists(fullPath); + } +} diff --git a/apps/windows/Keepassity.App/SingleInstanceRelay.Window.cs b/apps/windows/Keepassity.App/SingleInstanceRelay.Window.cs new file mode 100644 index 0000000..86d4416 --- /dev/null +++ b/apps/windows/Keepassity.App/SingleInstanceRelay.Window.cs @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; + +namespace Keepassity.App; + +internal sealed partial class SingleInstanceRelay : IDisposable +{ + + private bool CreateWindow() + { + _window = CreateWindowEx(WsExToolWindow, "STATIC", RelayWindowTitle, WsPopup, + 0, 0, 0, 0, IntPtr.Zero, IntPtr.Zero, GetModuleHandle(null), IntPtr.Zero); + if (_window == IntPtr.Zero) + { + AppLog.Warn("single-instance relay: hidden window could not be created " + + $"(error {Marshal.GetLastPInvokeError()})"); + return false; + } + Marshal.SetLastPInvokeError(0); + _previousProc = SetWindowLongPtr(_window, GwlWndProc, + Marshal.GetFunctionPointerForDelegate(_windowProc)); + int error = Marshal.GetLastPInvokeError(); + if (_previousProc == IntPtr.Zero && error != 0) + { + AppLog.Warn($"single-instance relay: window procedure hook failed (error {error})"); + _ = DestroyWindow(_window); + _window = IntPtr.Zero; + return false; + } + return true; + } + + private IntPtr WindowProc(IntPtr hWnd, uint message, IntPtr wParam, IntPtr lParam) + { + try + { + if (!_disposed && message == WmCopyData) + { + if (TryReadOpenRequest(wParam, lParam, out string? databasePath) && + databasePath is not null) + { + AppLog.Info("open request received from another instance"); + _onDatabasePath(databasePath); + return new IntPtr(1); + } + return IntPtr.Zero; + } + } + catch (Exception ex) + { + // A throwing window procedure would take down the process. + AppLog.Error("single-instance relay: request handling failed", ex); + } + return CallWindowProc(_previousProc, hWnd, message, wParam, lParam); + } + + private static bool TryReadOpenRequest(IntPtr senderWindow, IntPtr lParam, + out string? databasePath) + { + databasePath = null; + if (senderWindow == IntPtr.Zero || lParam == IntPtr.Zero) + { + Reject("the sender window is missing"); + return false; + } + _ = GetWindowThreadProcessId(senderWindow, out uint senderProcessId); + if (senderProcessId == 0 || senderProcessId == (uint)Environment.ProcessId) + { + Reject("the sender process is invalid"); + return false; + } + if (!IsSameApplication(senderProcessId)) + { + Reject("the sender process is not keepassity"); + return false; + } + CopyDataStruct data = Marshal.PtrToStructure(lParam); + if (data.Signature != new IntPtr(Magic)) + { + Reject("the payload signature is wrong"); + return false; + } + if (data.Data == IntPtr.Zero || data.Size <= 0 || + data.Size > MaxPayloadBytes || data.Size % 2 != 0) + { + Reject("the payload size is invalid"); + return false; + } + byte[] payload = new byte[data.Size]; + Marshal.Copy(data.Data, payload, 0, payload.Length); + string? decoded = DecodePath(payload); + if (decoded is null || + !TryNormalizeDatabasePath(decoded, out string fullPath)) + { + Reject("the payload is not an existing .kdbx path"); + return false; + } + databasePath = fullPath; + return true; + } + + private static void Reject(string reason) + { + AppLog.Warn($"single-instance relay: ignored an open request ({reason})"); + } + + private static bool IsSameApplication(uint processId) + { + string? expectedName = Path.GetFileName(Environment.ProcessPath); + if (string.IsNullOrEmpty(expectedName)) + { + return true; + } + try + { + using Process process = Process.GetProcessById((int)processId); + string actualName = process.ProcessName + ".exe"; + return string.Equals(actualName, expectedName, StringComparison.OrdinalIgnoreCase); + } + catch + { + // The process may have exited or the sandbox may deny the query; the + // payload itself is still validated, so do not drop a valid request. + AppLog.Warn("single-instance relay: sender process name could not be checked"); + return true; + } + } + + private static IntPtr SetWindowLongPtr(IntPtr window, int index, IntPtr value) + => IntPtr.Size == 8 + ? SetWindowLongPtr64(window, index, value) + : new IntPtr(SetWindowLong32(window, index, value.ToInt32())); +} diff --git a/apps/windows/Keepassity.App/SingleInstanceRelay.cs b/apps/windows/Keepassity.App/SingleInstanceRelay.cs new file mode 100644 index 0000000..046377a --- /dev/null +++ b/apps/windows/Keepassity.App/SingleInstanceRelay.cs @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; + +namespace Keepassity.App; + + +/// +/// Minimal cross-process hand-off for "open this .kdbx" requests, used when a +/// second keepassity launch (Explorer double-click / "Open with") should switch +/// the already-running instance instead of doing nothing. +/// +/// The running instance owns a tiny hidden top-level window whose title is +/// derived from the executable path; the second instance finds it with +/// FindWindow, verifies the owning process is the same application, and sends +/// the database path with WM_COPYDATA. The receiver validates the payload +/// (signature, size, sender process, existing .kdbx path) before handing the +/// path to the UI. This is the classic Win32 single-instance pattern and needs +/// no new dependency; an in-place activation (AppInstance redirection) would +/// require restructuring the app's launch path and is deliberately not used. +/// +internal sealed partial class SingleInstanceRelay : IDisposable +{ + private const int WmCopyData = 0x004A; + private const int GwlWndProc = -4; + private const uint Magic = 0x4B504458; // 'KPDX' + private const uint WsPopup = 0x80000000; + private const uint WsExToolWindow = 0x00000080; + private const uint SmtoBlock = 0x0001; + private const uint SmtoAbortIfHung = 0x0002; + private const uint SendTimeoutMilliseconds = 2000; + + /// Generous upper bound for a Windows path in UTF-16 bytes. + internal const int MaxPayloadBytes = 64 * 1024; + + /// Maximum path length Windows itself accepts (32767 characters). + internal const int MaxPathCharacters = 32767; + + private static readonly Lazy LazyRelayWindowTitle = new(() => + { + string executable = Environment.ProcessPath ?? "keepassity"; + byte[] hash = SHA256.HashData( + Encoding.UTF8.GetBytes(executable.ToLowerInvariant())); + // Deliberately does not contain "keepassity": the helper windows must not + // be mistaken for the main window by the activation fallback. + return "kdbx-open-relay-" + Convert.ToHexString(hash)[..16].ToLowerInvariant(); + }); + + private readonly Action _onDatabasePath; + // The window procedure holds a raw pointer to this delegate; keep it rooted. + private readonly SubclassProc _windowProc; + private IntPtr _window; + private IntPtr _previousProc; + private bool _disposed; + + [UnmanagedFunctionPointer(CallingConvention.Winapi)] + private delegate IntPtr SubclassProc(IntPtr hWnd, uint message, IntPtr wParam, + IntPtr lParam); + + [StructLayout(LayoutKind.Sequential)] + private struct CopyDataStruct + { + public IntPtr Signature; + public int Size; + public IntPtr Data; + } + + private SingleInstanceRelay(Action onDatabasePath) + { + _onDatabasePath = onDatabasePath; + _windowProc = WindowProc; + } + + /// Window title the receiving instance registers for discovery. + internal static string RelayWindowTitle => LazyRelayWindowTitle.Value; + + /// + /// Creates the hidden relay window for this process. Returns null (and logs) + /// when the window cannot be created; the app keeps working without IPC. + /// + public static SingleInstanceRelay? TryStart(Action onDatabasePath) + { + var relay = new SingleInstanceRelay(onDatabasePath); + bool created = false; + try + { + created = relay.CreateWindow(); + if (created) + { + AppLog.Info("single-instance relay window ready"); + return relay; + } + } + catch (Exception ex) + { + AppLog.Error("single-instance relay could not be started", ex); + } + finally + { + // Always release the partially created window, also when logging or + // window creation threw (CodeQL cs/dispose-not-called-on-throw). + if (!created) + { + relay.Dispose(); + } + } + return null; + } + + public void Dispose() + { + if (_disposed) + { + return; + } + _disposed = true; + try + { + if (_window != IntPtr.Zero) + { + if (_previousProc != IntPtr.Zero) + { + _ = SetWindowLongPtr(_window, GwlWndProc, _previousProc); + _previousProc = IntPtr.Zero; + } + _ = DestroyWindow(_window); + _window = IntPtr.Zero; + AppLog.Info("single-instance relay window closed"); + } + } + catch (Exception ex) + { + AppLog.Error("single-instance relay cleanup failed", ex); + } + } + + [DllImport("user32.dll", EntryPoint = "SetWindowLongPtrW", SetLastError = true)] + private static extern IntPtr SetWindowLongPtr64(IntPtr window, int index, IntPtr value); + + [DllImport("user32.dll", EntryPoint = "SetWindowLongW", SetLastError = true)] + private static extern int SetWindowLong32(IntPtr window, int index, int value); + + [DllImport("user32.dll", SetLastError = true)] + private static extern IntPtr CallWindowProc(IntPtr previousProc, IntPtr window, + uint message, IntPtr wParam, IntPtr lParam); + + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr CreateWindowEx(uint exStyle, string className, + string windowName, uint style, int x, int y, int width, int height, + IntPtr parent, IntPtr menu, IntPtr instance, IntPtr param); + + [DllImport("user32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool DestroyWindow(IntPtr window); + + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr FindWindow(string? className, string? windowName); + + [DllImport("user32.dll", SetLastError = true)] + private static extern IntPtr SendMessageTimeout(IntPtr window, uint message, + IntPtr wParam, IntPtr lParam, uint flags, uint timeout, out IntPtr result); + + [DllImport("user32.dll", SetLastError = true)] + private static extern uint GetWindowThreadProcessId(IntPtr window, out uint processId); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + private static extern IntPtr GetModuleHandle(string? moduleName); +} diff --git a/apps/windows/Keepassity.Mock/TestHooks.cs b/apps/windows/Keepassity.App/TestHooks.cs similarity index 87% rename from apps/windows/Keepassity.Mock/TestHooks.cs rename to apps/windows/Keepassity.App/TestHooks.cs index 62ab7dd..23aecf1 100644 --- a/apps/windows/Keepassity.Mock/TestHooks.cs +++ b/apps/windows/Keepassity.App/TestHooks.cs @@ -1,10 +1,13 @@ // SPDX-License-Identifier: GPL-3.0-or-later -namespace Keepassity.Mock; +namespace Keepassity.App; /// /// Opt-in gate for the diagnostic overrides that exist for automated UI checks: /// --allow-multiple, --no-tray, KEEPASSITY_MOCK_PASSWORD, -/// KEEPASSITY_SETTINGS_DEMO_MS and the tray-menu geometry hooks. +/// KEEPASSITY_LANGUAGE (forces the UI language at startup without saving +/// it), KEEPASSITY_SETTINGS_DEMO_MS, the tray-menu geometry hooks and +/// KEEPASSITY_RELOAD_AFTER_DRAG_MS (reopens the vault a moment after a +/// drag-move, reproducing the delayed merge refresh for scroll checks). /// /// They are useful when testing a published build, but a normal user (or a /// malicious environment variable) must not be able to skip the single-instance diff --git a/apps/windows/Keepassity.App/TrayIcon.Icon.cs b/apps/windows/Keepassity.App/TrayIcon.Icon.cs new file mode 100644 index 0000000..dedcc24 --- /dev/null +++ b/apps/windows/Keepassity.App/TrayIcon.Icon.cs @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using H.NotifyIcon; +using H.NotifyIcon.Core; +using Microsoft.UI.Windowing; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Controls.Primitives; +using Microsoft.UI.Xaml.Media; +using System.Runtime.InteropServices; +using Windows.UI; +using WinRT.Interop; + +namespace Keepassity.App; + +public sealed partial class TrayIcon : IDisposable +{ + + private bool TrySetApplicationIcon(string? iconPath) + { + if (string.IsNullOrWhiteSpace(iconPath) || !File.Exists(iconPath)) + { + AppLog.Warn("tray icon: app.ico asset is missing; using the generated fallback"); + return false; + } + try + { + _ownedIcon = new System.Drawing.Icon(iconPath); + _icon.Icon = _ownedIcon; + AppLog.Info("tray icon: loaded Assets/app.ico"); + return true; + } + catch (Exception ex) + { + AppLog.Error("tray icon: app.ico could not be loaded", ex); + return false; + } + } + + public void ApplyTheme(ElementTheme theme) + { + _theme = theme; + _icon.RequestedTheme = theme; + if (_anchorWindow?.Content is FrameworkElement root) + { + root.RequestedTheme = theme; + } + } + + private static void MakeTransparent(nint handle) + { + nint style = GetWindowLongPtr(handle, GwlExStyle); + style |= WsExToolWindow | WsExTransparent | WsExLayered; + _ = SetWindowLongPtr(handle, GwlExStyle, style); + _ = SetLayeredWindowAttributes(handle, 0, 0, LwaAlpha); + } + + private static FontIcon CreateIcon(string glyph) => new() { Glyph = glyph, FontSize = 14 }; +} diff --git a/apps/windows/Keepassity.App/TrayIcon.Menu.cs b/apps/windows/Keepassity.App/TrayIcon.Menu.cs new file mode 100644 index 0000000..c596464 --- /dev/null +++ b/apps/windows/Keepassity.App/TrayIcon.Menu.cs @@ -0,0 +1,294 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using H.NotifyIcon; +using H.NotifyIcon.Core; +using Microsoft.UI.Windowing; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Controls.Primitives; +using Microsoft.UI.Xaml.Media; +using System.Runtime.InteropServices; +using Windows.UI; +using WinRT.Interop; + +namespace Keepassity.App; + +public sealed partial class TrayIcon : IDisposable +{ + + /// + /// Test hook: opens the context menu at a physical screen position so an + /// automated capture can inspect the rendered menu without pointer input. + /// + public void ShowMenuAt(int x, int y) + { + if (_disposed) + { + return; + } + ShowMenu(x, y, 0, 0); + } + + /// + /// Test hook: opens the context menu anchored to the notification icon (the + /// same path a real right-click uses) instead of at explicit coordinates. + /// + public void ShowMenuAtIconForTest() + { + if (_disposed) + { + return; + } + OpenMenuAtIcon(); + } + + private void OpenMenuAtIcon() + { + if (_disposed) + { + return; + } + if (TryGetIconRect(out int x, out int y, out int width, out int height)) + { + ShowMenu(x, y, width, height); + return; + } + if (GetCursorPos(out NativePoint point)) + { + ShowMenu(point.X, point.Y, 0, 0); + } + } + + private bool TryGetIconRect(out int x, out int y, out int width, out int height) + { + x = y = width = height = 0; + try + { + H.NotifyIcon.Core.TrayIcon tray = _icon.TrayIcon; + if (tray is null) + { + return false; + } + NotifyIconIdentifier identifier = new() + { + Size = (uint)Marshal.SizeOf(), + Window = (IntPtr)tray.WindowHandle, + Id = 0, + Guid = tray.Id, + }; + int hresult = Shell_NotifyIconGetRect(ref identifier, out NativeRect rect); + if (hresult < 0 || rect.Right <= rect.Left || rect.Bottom <= rect.Top) + { + return false; + } + x = rect.Left; + y = rect.Top; + width = rect.Right - rect.Left; + height = rect.Bottom - rect.Top; + return true; + } + catch + { + return false; + } + } + + private void ShowMenu(int x, int y, int iconWidth, int iconHeight) + { + if (_menu.IsOpen) + { + CloseMenu(); + return; + } + EnsureAnchorWindow(); + if (_anchorWindow is null || _anchor is null) + { + return; + } + try + { + _previousForeground = GetForegroundWindow(); + _actionInvoked = false; + _iconWidth = iconWidth; + _iconHeight = iconHeight; + _anchorX = x; + _anchorY = y; + _anchorWindow.AppWindow.MoveAndResize( + new Windows.Graphics.RectInt32(x, y, 1, 1)); + if (!_anchorLoaded || _anchor.XamlRoot is null) + { + _anchor.Loaded -= OnAnchorLoaded; + _anchor.Loaded += OnAnchorLoaded; + _anchorWindow.AppWindow.Show(); + return; + } + PresentMenu(); + } + catch (Exception ex) + { + AppLog.Error("tray menu failed to open", ex); + } + } + + private void OnAnchorLoaded(object sender, RoutedEventArgs e) + { + _anchor!.Loaded -= OnAnchorLoaded; + _anchorLoaded = true; + PresentMenu(); + } + + private void PresentMenu() + { + if (_disposed || _anchorWindow is null || _anchor is null || _menu.IsOpen) + { + return; + } + nint handle = WindowNative.GetWindowHandle(_anchorWindow); + double scale = _anchor.XamlRoot?.RasterizationScale ?? 1.0; + _anchorWindow.Activate(); + _anchorWindow.AppWindow.Show(); + _ = SetForegroundWindow(handle); + try + { + _menu.ShowAt(_anchor, new FlyoutShowOptions + { + Position = new Windows.Foundation.Point(0, 0), + Placement = ChoosePlacement(), + ExclusionRect = new Windows.Foundation.Rect( + 0, 0, _iconWidth / scale, _iconHeight / scale), + }); + AppLog.Info("tray menu shown"); + } + catch (Exception ex) + { + AppLog.Error("tray menu failed to open", ex); + } + } + + /// + /// Picks the side of the anchor with more room. Menus anchored near the top + /// edge (top taskbar) open down and to the right; menus near the bottom edge + /// open up. Near the right edge the menu is right-aligned to stay on screen. + /// + private FlyoutPlacementMode ChoosePlacement() + { + DisplayArea area = DisplayArea.GetFromPoint( + new Windows.Graphics.PointInt32(_anchorX, _anchorY), + DisplayAreaFallback.Nearest); + Windows.Graphics.RectInt32 work = area.WorkArea; + TrayMenuPlacement.Result placement = TrayMenuPlacement.Choose( + _anchorX, _anchorY, _iconWidth, _iconHeight, + work.Y, work.X + work.Width, work.Y + work.Height); + bool below = placement.Side == TrayMenuPlacement.VerticalSide.Below; + return below + ? (placement.RightAligned + ? FlyoutPlacementMode.BottomEdgeAlignedRight + : FlyoutPlacementMode.BottomEdgeAlignedLeft) + : (placement.RightAligned + ? FlyoutPlacementMode.TopEdgeAlignedRight + : FlyoutPlacementMode.TopEdgeAlignedLeft); + } + + private void OnMenuOpened(object? sender, object e) + { + // The flyout presenter is a separate visual root and does not inherit the + // app theme from the anchor element, so pin the theme explicitly. + if (sender is FrameworkElement presenter) + { + presenter.RequestedTheme = _theme; + } + AppLog.Info("tray menu opened"); + } + + private void CloseMenu() + { + try + { + _menu.Hide(); + } + catch (Exception ex) + { + AppLog.Error("tray menu failed to close", ex); + } + } + + private void OnMenuClosed() + { + AppLog.Info("tray menu closed"); + try + { + _anchorWindow?.AppWindow.Hide(); + } + catch + { + // Best-effort cleanup. + } + RestorePreviousForeground(); + } + + private void RestorePreviousForeground() + { + IntPtr previous = _previousForeground; + _previousForeground = IntPtr.Zero; + if (previous == IntPtr.Zero || _actionInvoked || _disposed) + { + return; + } + IntPtr foreground = GetForegroundWindow(); + _ = GetWindowThreadProcessId(foreground, out uint foregroundProcess); + if (foregroundProcess != (uint)Environment.ProcessId) + { + // The user dismissed the menu by activating another application; + // leave that application in front. + return; + } + _ = SetForegroundWindow(previous); + } + + private void EnsureAnchorWindow() + { + if (_anchorWindow is not null) + { + return; + } + + _anchor = new Border + { + Width = 1, + Height = 1, + HorizontalAlignment = HorizontalAlignment.Left, + VerticalAlignment = VerticalAlignment.Top, + Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent), + }; + var root = new Grid + { + RequestedTheme = _theme, + Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent), + }; + root.Children.Add(_anchor); + + var window = new Window { Content = root }; + nint handle = WindowNative.GetWindowHandle(window); + Microsoft.UI.WindowId windowId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(handle); + AppWindow appWindow = AppWindow.GetFromWindowId(windowId); + appWindow.IsShownInSwitchers = false; + if (appWindow.Presenter is OverlappedPresenter presenter) + { + presenter.IsAlwaysOnTop = true; + presenter.IsResizable = false; + presenter.IsMaximizable = false; + presenter.IsMinimizable = false; + presenter.SetBorderAndTitleBar(false, false); + } + MakeTransparent(handle); + window.Activated += (_, args) => + { + if (args.WindowActivationState == WindowActivationState.Deactivated && _menu.IsOpen) + { + CloseMenu(); + } + }; + appWindow.Hide(); + _anchorWindow = window; + AppLog.Info("tray menu anchor window ready"); + } +} diff --git a/apps/windows/Keepassity.App/TrayIcon.State.cs b/apps/windows/Keepassity.App/TrayIcon.State.cs new file mode 100644 index 0000000..ff5074d --- /dev/null +++ b/apps/windows/Keepassity.App/TrayIcon.State.cs @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using H.NotifyIcon; +using H.NotifyIcon.Core; +using Microsoft.UI.Windowing; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Controls.Primitives; +using Microsoft.UI.Xaml.Media; +using System.Runtime.InteropServices; +using Windows.UI; +using WinRT.Interop; + +namespace Keepassity.App; + +public sealed partial class TrayIcon : IDisposable +{ + + /// + /// Re-renders the menu and tooltip after the shell language changed. The flyout + /// items are reused (not recreated) so an open menu and the click handlers stay + /// valid; only their text is replaced. + /// + public void ApplyLanguage() + { + if (_disposed) + { + return; + } + _showItem.Text = Loc.T("Show Keepassity"); + _lockItem.Text = Loc.T("Lock"); + _exitItem.Text = Loc.T("Exit Keepassity"); + UpdateToolTip(); + } + + /// + /// Reflects the vault state in the menu and the tray tooltip. The Lock command + /// is only meaningful while a database is open. + /// + public void SetVaultState(bool unlocked, string? databaseName) + { + if (_disposed) + { + return; + } + _lockItem.IsEnabled = unlocked; + _unlocked = unlocked; + _databaseName = databaseName; + UpdateToolTip(); + } + + private void UpdateToolTip() + { + if (_disposed) + { + return; + } + string state = Loc.T(_unlocked ? "unlocked" : "locked"); + _icon.ToolTipText = string.IsNullOrWhiteSpace(_databaseName) + ? Loc.T("Keepassity - {0}", state) + : Loc.T("Keepassity - {0} ({1})", _databaseName, state); + } + + public void ShowInfo(string title, string message) + { + if (_disposed) + { + return; + } + _icon.ShowNotification(title, message); + } + + private static void Invoke(Action action) + { + try + { + action(); + } + catch + { + // A tray callback must not take down the application. + } + } + + private sealed class TrayCommand : System.Windows.Input.ICommand + { + private readonly Action _action; + + public TrayCommand(Action action) => _action = action; + + public event EventHandler? CanExecuteChanged + { + add { } + remove { } + } + + public bool CanExecute(object? parameter) => true; + + public void Execute(object? parameter) => Invoke(_action); + } +} diff --git a/apps/windows/Keepassity.App/TrayIcon.cs b/apps/windows/Keepassity.App/TrayIcon.cs new file mode 100644 index 0000000..6cd7308 --- /dev/null +++ b/apps/windows/Keepassity.App/TrayIcon.cs @@ -0,0 +1,239 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using H.NotifyIcon; +using H.NotifyIcon.Core; +using Microsoft.UI.Windowing; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Controls.Primitives; +using Microsoft.UI.Xaml.Media; +using System.Runtime.InteropServices; +using Windows.UI; +using WinRT.Interop; + +namespace Keepassity.App; + + +/// +/// WinUI notification-area icon with a native WinUI menu surface. +/// +/// There is no first-party tray-icon API in WinUI 3; the supported approach is +/// Shell_NotifyIcon (provides the icon and the WM_CONTEXTMENU callback) plus a +/// WinUI for the menu. A flyout needs a XamlRoot, so a +/// small invisible host window is moved to the notification icon before showing +/// the menu. This is the same pattern the WinUIEx TrayIcon uses: the host is +/// positioned with Shell_NotifyIconGetRect, the flyout is shown with +/// Position=(0,0) and an ExclusionRect covering the icon, and the host takes the +/// foreground so the menu is above the taskbar and the overflow flyout. +/// +public sealed partial class TrayIcon : IDisposable +{ + private const int GwlExStyle = -20; + private const nint WsExTransparent = 0x00000020; + private const nint WsExToolWindow = 0x00000080; + private const nint WsExLayered = 0x00080000; + private const uint LwaAlpha = 0x00000002; + + private readonly TaskbarIcon _icon; + private readonly MenuFlyout _menu; + private readonly MenuFlyoutItem _showItem; + private readonly MenuFlyoutItem _lockItem; + private readonly MenuFlyoutItem _exitItem; + private System.Drawing.Icon? _ownedIcon; + private Window? _anchorWindow; + private Border? _anchor; + private ElementTheme _theme; + private IntPtr _previousForeground; + private bool _actionInvoked; + private bool _anchorLoaded; + private bool _disposed; + private bool _unlocked; + private string? _databaseName; + + [StructLayout(LayoutKind.Sequential)] + private struct NativePoint + { + public int X; + public int Y; + } + + [StructLayout(LayoutKind.Sequential)] + private struct NativeRect + { + public int Left; + public int Top; + public int Right; + public int Bottom; + } + + [StructLayout(LayoutKind.Sequential)] + private struct NotifyIconIdentifier + { + public uint Size; + public IntPtr Window; + public uint Id; + public Guid Guid; + } + + [DllImport("user32.dll")] + private static extern bool GetCursorPos(out NativePoint point); + + [DllImport("user32.dll")] + private static extern IntPtr GetForegroundWindow(); + + [DllImport("user32.dll")] + private static extern bool SetForegroundWindow(IntPtr window); + + [DllImport("user32.dll")] + private static extern uint GetWindowThreadProcessId(IntPtr window, out uint processId); + + [DllImport("user32.dll")] + private static extern nint GetWindowLongPtr(nint window, int index); + + [DllImport("user32.dll")] + private static extern nint SetWindowLongPtr(nint window, int index, nint value); + + [DllImport("user32.dll")] + private static extern bool SetLayeredWindowAttributes(nint window, uint colorKey, + byte alpha, uint flags); + + [DllImport("shell32.dll")] + private static extern int Shell_NotifyIconGetRect(ref NotifyIconIdentifier identifier, + out NativeRect iconLocation); + + public TrayIcon(string toolTip, ElementTheme theme, string? iconPath, Action show, + Action lockAction, Action exit) + { + _theme = theme; + + var showItem = new MenuFlyoutItem + { + Text = Loc.T("Show Keepassity"), + Icon = CreateIcon("\uE8A7"), + }; + _showItem = showItem; + showItem.Click += (_, _) => + { + _actionInvoked = true; + Invoke(show); + }; + + _lockItem = new MenuFlyoutItem + { + Text = Loc.T("Lock"), + Icon = CreateIcon("\uE72E"), + IsEnabled = false, + }; + _lockItem.Click += (_, _) => + { + _actionInvoked = true; + Invoke(lockAction); + }; + + var exitItem = new MenuFlyoutItem + { + Text = Loc.T("Exit Keepassity"), + Icon = CreateIcon("\uE7E8"), + }; + _exitItem = exitItem; + exitItem.Click += (_, _) => + { + _actionInvoked = true; + Invoke(exit); + }; + + _menu = new MenuFlyout + { + Items = + { + showItem, + _lockItem, + new MenuFlyoutSeparator(), + exitItem, + }, + }; + _menu.Opened += OnMenuOpened; + _menu.Closed += (_, _) => OnMenuClosed(); + _menu.ShouldConstrainToRootBounds = false; + + _icon = new TaskbarIcon + { + ToolTipText = toolTip, + MenuActivation = PopupActivationMode.None, + RequestedTheme = theme, + NoLeftClickDelay = true, + LeftClickCommand = new TrayCommand(show), + DoubleClickCommand = new TrayCommand(show), + RightClickCommand = new TrayCommand(OpenMenuAtIcon), + }; + // Prefer the real application artwork. H.NotifyIcon accepts a + // System.Drawing.Icon directly for the notification-area icon; the + // framework keeps using the icon for the lifetime of the tray icon, so + // the instance is owned and disposed here. + if (!TrySetApplicationIcon(iconPath)) + { + _icon.IconSource = new GeneratedIconSource + { + Text = "K", + FontSize = 34, + FontWeight = Microsoft.UI.Text.FontWeights.Bold, + Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255)), + Background = new SolidColorBrush(Color.FromArgb(255, 0, 120, 212)), + }; + } + _icon.ForceCreate(); + } + + public bool Available => !_disposed && _icon.IsCreated; + + public UIElement? Element => _icon; + + private int _iconWidth; + private int _iconHeight; + private int _anchorX; + private int _anchorY; + + public void Dispose() + { + if (_disposed) + { + return; + } + if (_menu.IsOpen) + { + try + { + _menu.Hide(); + } + catch + { + // Best-effort cleanup. + } + } + _disposed = true; + try + { + _anchorWindow?.Close(); + } + catch + { + // Best-effort cleanup. + } + try + { + _icon.Dispose(); + } + catch + { + // Best-effort cleanup. + } + try + { + _ownedIcon?.Dispose(); + _ownedIcon = null; + } + catch + { + // Best-effort cleanup. + } + } +} diff --git a/apps/windows/Keepassity.Mock/app.manifest b/apps/windows/Keepassity.App/app.manifest similarity index 100% rename from apps/windows/Keepassity.Mock/app.manifest rename to apps/windows/Keepassity.App/app.manifest diff --git a/apps/windows/Keepassity.Mock/packages.lock.json b/apps/windows/Keepassity.App/packages.lock.json similarity index 91% rename from apps/windows/Keepassity.Mock/packages.lock.json rename to apps/windows/Keepassity.App/packages.lock.json index fecd3b7..11b5399 100644 --- a/apps/windows/Keepassity.Mock/packages.lock.json +++ b/apps/windows/Keepassity.App/packages.lock.json @@ -1,7 +1,7 @@ { "version": 2, "dependencies": { - "net8.0-windows10.0.19041": { + "net10.0-windows10.0.19041": { "H.NotifyIcon.WinUI": { "type": "Direct", "requested": "[2.3.2, )", @@ -9,9 +9,7 @@ "contentHash": "UoI3z3Kc/6gBC6gOrL/cKhGAf6wz8gxk6wc0lYQZZYwSfU3OMpnKOdWJ5c1PXMaaJi/QMKYHN/ilpB7uHGUOpg==", "dependencies": { "H.NotifyIcon": "2.3.2", - "Microsoft.WindowsAppSDK": "1.6.250108002", - "System.Collections.Immutable": "9.0.1", - "System.Reflection.Metadata": "9.0.1" + "Microsoft.WindowsAppSDK": "1.6.250108002" } }, "Microsoft.WindowsAppSDK": { @@ -153,11 +151,6 @@ "Microsoft.WindowsAppSDK.InteractiveExperiences": "1.8.260708001" } }, - "System.Collections.Immutable": { - "type": "Transitive", - "resolved": "9.0.1", - "contentHash": "qt4+ClsZYKzar/Rw1zbt0t9iuBUCLVNsjXicEuVQyKL7143CwhWzI2gTwzz8AhSaFYVHnpcb8SBGA+zaY4weUg==" - }, "System.Drawing.Common": { "type": "Transitive", "resolved": "9.0.1", @@ -171,19 +164,24 @@ "resolved": "9.0.0", "contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A==" }, - "System.Reflection.Metadata": { - "type": "Transitive", - "resolved": "9.0.1", - "contentHash": "XGkA0wiS4vbZu708VtlgSh40stW2ucDriDItkiJUnnp867x5HaBfmoTqdA00DYG0Ld7Kg0cLvEPkUEUxputgzQ==", + "keepassity.core": { + "type": "Project" + }, + "keepassity.viewmodels": { + "type": "Project", "dependencies": { - "System.Collections.Immutable": "9.0.1" + "CommunityToolkit.Mvvm": "[8.4.2, )", + "Keepassity.Core": "[1.0.0, )" } }, - "keepassity.core": { - "type": "Project" + "CommunityToolkit.Mvvm": { + "type": "CentralTransitive", + "requested": "[8.4.2, )", + "resolved": "8.4.2", + "contentHash": "WadCzGEc2U+3e20avRLng4qNtt4zoOGWrdUISqJWrHe3/FSnrYjuM5Sb4yQb09LhkBXrrI4Zt3dLKgRMbItsrg==" } }, - "net8.0-windows10.0.19041/win-x64": { + "net10.0-windows10.0.19041/win-x64": { "Microsoft.Web.WebView2": { "type": "Transitive", "resolved": "1.0.3179.45", diff --git a/apps/windows/Keepassity.Core/AppLog.cs b/apps/windows/Keepassity.Core/AppLog.cs index 102867a..a0e8647 100644 --- a/apps/windows/Keepassity.Core/AppLog.cs +++ b/apps/windows/Keepassity.Core/AppLog.cs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later using System.Text; -namespace Keepassity.Mock; +namespace Keepassity.Core; /// /// Minimal local file logger. Logs stay on the machine, never leave it, and never @@ -13,6 +13,7 @@ public static class AppLog private static readonly object Gate = new(); private static bool _initialized; private static string? _directory; + private static LogFile? _log; public static string DirectoryPath { @@ -22,7 +23,7 @@ public static string DirectoryPath { return _directory; } - return Path.Combine(AppDataPaths.Root, "logs"); + return Path.Combine(ApplicationPaths.Root, "logs"); } } @@ -33,16 +34,18 @@ public static void Initialize() return; } _initialized = true; - string directory = Path.Combine(AppDataPaths.Root, "logs"); + string directory = Path.Combine(ApplicationPaths.Root, "logs"); try { Directory.CreateDirectory(directory); _directory = directory; - Prune(directory); + _log = new LogFile(directory); + _log.Prune(DateTimeOffset.Now, RetentionDays); } catch { _directory = null; + _log = null; } Info($"application started (pid {Environment.ProcessId})"); } @@ -61,7 +64,8 @@ private static void Write(string level, string message, Exception? exception) Initialize(); } string? directory = _directory; - if (directory is null) + LogFile? log = _log; + if (directory is null || log is null) { return; } @@ -77,9 +81,7 @@ private static void Write(string level, string message, Exception? exception) { lock (Gate) { - string path = Path.Combine( - directory, $"app-{DateTime.Now:yyyyMMdd}.log"); - File.AppendAllText(path, line.ToString() + Environment.NewLine, Encoding.UTF8); + log.Append(line.ToString(), DateTimeOffset.Now); } } catch @@ -87,23 +89,4 @@ private static void Write(string level, string message, Exception? exception) // Logging must never break the application. } } - - private static void Prune(string directory) - { - try - { - DateTime cutoff = DateTime.Now.AddDays(-RetentionDays); - foreach (string file in Directory.EnumerateFiles(directory, "app-*.log")) - { - if (File.GetLastWriteTime(file) < cutoff) - { - File.Delete(file); - } - } - } - catch - { - // Best effort. - } - } } diff --git a/apps/windows/Keepassity.Core/AppSettingsStore.cs b/apps/windows/Keepassity.Core/AppSettingsStore.cs index a41397c..5c14a80 100644 --- a/apps/windows/Keepassity.Core/AppSettingsStore.cs +++ b/apps/windows/Keepassity.Core/AppSettingsStore.cs @@ -1,13 +1,19 @@ // SPDX-License-Identifier: GPL-3.0-or-later using System.Text.Json; -namespace Keepassity.Mock; +namespace Keepassity.Core; public sealed class AppSettings { /// Schema version of this settings file; bump when fields change meaning. public int SchemaVersion { get; set; } = 1; public string Theme { get; set; } = "Dark"; + /// + /// UI language: system follows the Windows display language, or an + /// explicit tag such as en / zh-CN. The Windows shell applies it + /// through Loc at startup and when Settings changes it. + /// + public string Language { get; set; } = "system"; public bool ClearClipboardAfter30Seconds { get; set; } = true; public bool AutoLockEnabled { get; set; } = true; public int AutoLockMinutes { get; set; } = 15; @@ -36,33 +42,62 @@ public sealed class AppSettings public sealed class AppSettingsStore { + private const int CurrentSchema = 1; + private static readonly JsonSerializerOptions Options = new() { WriteIndented = true, }; private readonly string _path; + private readonly bool _readOnly; + private bool _warnedReadOnly; - public AppSettingsStore() + /// + /// is for tests and diagnostics; the app uses the + /// application data root. + /// + public AppSettingsStore(string? path = null) { - string directory = AppDataPaths.Root; - try + if (string.IsNullOrWhiteSpace(path)) { - Directory.CreateDirectory(directory); + string directory = ApplicationPaths.Root; + try + { + Directory.CreateDirectory(directory); + } + catch + { + // Read-only fallback: settings still load if the file exists, and + // Save() below is best-effort. + } + _path = Path.Combine(directory, "settings.json"); } - catch + else { - // Read-only fallback: settings still load if the file exists, and - // Save() below is best-effort. + _path = Path.GetFullPath(path); + string? directory = Path.GetDirectoryName(_path); + if (!string.IsNullOrEmpty(directory)) + { + Directory.CreateDirectory(directory); + } } - _path = Path.Combine(directory, "settings.json"); - Current = Load(); + Current = Load(out bool readOnly); + _readOnly = readOnly; } public AppSettings Current { get; } - private AppSettings Load() + /// + /// True when the file was written by a newer schema. Saving in that state + /// would silently discard fields this build does not understand, so Save() + /// leaves the file untouched. + /// + public bool IsReadOnly => _readOnly; + + private AppSettings Load(out bool readOnly) { + readOnly = false; try { if (File.Exists(_path)) @@ -73,11 +108,13 @@ private AppSettings Load() { if (loaded.SchemaVersion <= 0) { - loaded.SchemaVersion = 1; + loaded.SchemaVersion = CurrentSchema; } - else if (loaded.SchemaVersion > 1) + else if (loaded.SchemaVersion > CurrentSchema) { - AppLog.Warn($"settings schema {loaded.SchemaVersion} is newer than supported"); + readOnly = true; + AppLog.Warn($"settings schema {loaded.SchemaVersion} is newer than " + + $"supported ({CurrentSchema}); not overwriting it"); } return loaded; } @@ -85,23 +122,51 @@ private AppSettings Load() } catch { - // Corrupt or unreadable settings fall back to defaults; no vault data - // is stored in this file. + // Corrupt or unreadable settings fall back to defaults, but keep the + // original bytes for diagnosis; vault data is never stored here. + PreserveCorruptFile(); + return new AppSettings(); } + PreserveCorruptFile(); return new AppSettings(); } public void Save() { + if (_readOnly) + { + if (!_warnedReadOnly) + { + _warnedReadOnly = true; + AppLog.Warn("settings save skipped: the on-disk settings have a newer schema"); + } + return; + } try { - string temp = _path + ".tmp"; - File.WriteAllText(temp, JsonSerializer.Serialize(Current, Options)); - File.Move(temp, _path, true); + AtomicFile.Write(_path, JsonSerializer.SerializeToUtf8Bytes(Current, Options)); } catch { // Preferences are best-effort; never block vault operations on them. } } + + private void PreserveCorruptFile() + { + try + { + if (!File.Exists(_path)) + { + return; + } + string backup = _path + ".corrupt-" + DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + File.Copy(_path, backup, overwrite: false); + AppLog.Warn($"preserved unreadable settings as {Path.GetFileName(backup)}"); + } + catch + { + // Diagnostics must not prevent the app from starting. + } + } } diff --git a/apps/windows/Keepassity.Core/AppDataPaths.cs b/apps/windows/Keepassity.Core/ApplicationPaths.cs similarity index 94% rename from apps/windows/Keepassity.Core/AppDataPaths.cs rename to apps/windows/Keepassity.Core/ApplicationPaths.cs index 9ad8fe6..2fe5ad7 100644 --- a/apps/windows/Keepassity.Core/AppDataPaths.cs +++ b/apps/windows/Keepassity.Core/ApplicationPaths.cs @@ -1,11 +1,11 @@ // SPDX-License-Identifier: GPL-3.0-or-later -namespace Keepassity.Mock; +namespace Keepassity.Core; /// /// Local data root. Defaults to %LOCALAPPDATA%\keepassity; KEEPASSITY_DATA_DIR /// allows a portable/test data directory without touching the real profile. /// -public static class AppDataPaths +public static class ApplicationPaths { public static string Root { diff --git a/apps/windows/Keepassity.Core/AtomicFile.cs b/apps/windows/Keepassity.Core/AtomicFile.cs new file mode 100644 index 0000000..de3d181 --- /dev/null +++ b/apps/windows/Keepassity.Core/AtomicFile.cs @@ -0,0 +1,299 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +namespace Keepassity.Core; + +/// +/// Durable, verified-in-placement file replacement: write a sibling temporary +/// file with write-through and an explicit disk flush, take a timestamped backup +/// of the previous file, then replace atomically. The live file is never opened +/// for partial writes, so a crash leaves either the old or the new database. +/// +public static class AtomicFile +{ + /// + /// Marker between the database path and the random nonce. This is the same + /// convention as the core save protocol, so a crash-left temporary file can + /// be identified by either layer. + /// + public const string TempInfix = ".keepassity-tmp-"; + + /// + /// Place an already flushed temporary sibling at its destination. + /// gives the best + /// semantics (metadata and backup handling) but is unavailable on FAT/exFAT + /// and some network shares, where it fails with an IO error. The fallback is + /// a same-volume , which is also + /// a rename: a crash leaves either the old or the new file, and the caller has + /// already taken a backup. + /// + internal static void ReplaceFlushedTemp(string tempPath, string destinationPath, + bool allowFileReplace = true) + { + if (allowFileReplace) + { + try + { + File.Replace(tempPath, destinationPath, null, ignoreMetadataErrors: true); + return; + } + catch (Exception ex) when (ex is PlatformNotSupportedException or IOException) + { + AppLog.Warn($"File.Replace unavailable ({ex.Message}); falling back to a " + + "same-volume rename"); + } + } + File.Move(tempPath, destinationPath, overwrite: true); + } + + /// + /// Replace with , keeping + /// a backup of the previous file when it exists. + /// runs after the backup and + /// immediately before the rename: returning true aborts with a + /// so a file that another program changed during + /// the save is not silently overwritten. + /// + public static void Replace(string path, byte[] content, int backupRetention = 20, + string reason = "save", Func? changedBeforeReplace = null) + { + if (content is null || content.Length == 0) + { + throw new ArgumentException("Refusing to write an empty file.", nameof(content)); + } + string fullPath = Path.GetFullPath(path); + string directory = Path.GetDirectoryName(fullPath)!; + Directory.CreateDirectory(directory); + string temp = Path.Combine(directory, + Path.GetFileName(fullPath) + TempInfix + Guid.NewGuid().ToString("N")); + try + { + using (var stream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, + FileShare.None, 4096, FileOptions.WriteThrough)) + { + stream.Write(content); + stream.Flush(flushToDisk: true); + } + if (File.Exists(fullPath)) + { + BackupService.CreateBackup(fullPath, backupRetention, reason); + if (changedBeforeReplace?.Invoke() == true) + { + throw new CoreException("VaultChanged", + "the database changed outside this window"); + } + ReplaceFlushedTemp(temp, fullPath); + } + else + { + File.Move(temp, fullPath); + } + } + finally + { + if (File.Exists(temp)) + { + try + { + File.Delete(temp); + } + catch + { + // The replacement is what matters; a scanner may still hold + // the temporary file, which is harmless and clearly named. + } + } + } + } + + /// + /// Remove temporary files left by a crash for . Only + /// names matching the protocol are touched; the live database and unrelated + /// files are never deleted. Legacy dot-prefixed names from older builds are + /// included. + /// + public static int CleanupResidualTemps(string path) + { + string fullPath = Path.GetFullPath(path); + string? directory = Path.GetDirectoryName(fullPath); + if (string.IsNullOrEmpty(directory) || !Directory.Exists(directory)) + { + return 0; + } + string name = Path.GetFileName(fullPath); + string[] candidates = + { + name + TempInfix, + "." + name + TempInfix, + name + ".restore-tmp-", + "." + name + ".restore-tmp-", + }; + int removed = 0; + foreach (string prefix in candidates) + { + foreach (string candidate in Directory.EnumerateFiles(directory, prefix + "*")) + { + // A concurrent save would have the file open with FileShare.None; + // deletion fails and the next cleanup retries. The vault lock + // means this should not happen during a normal save. + try + { + File.Delete(candidate); + removed++; + } + catch + { + // Leave it; it is clearly named and not the live file. + } + } + } + return removed; + } + + /// + /// Removes crash residue under the application data folder. Only files whose + /// name carries one of the protocol infixes are considered, and only when + /// they are older than so a concurrent test + /// instance's write is never disturbed. Returns the number removed. + /// + public static int CleanupResidualTempsInTree(string root, TimeSpan olderThan) + { + try + { + string fullRoot = Path.GetFullPath(root); + if (!Directory.Exists(fullRoot)) + { + return 0; + } + return CleanupResidualTempsInDirectory(fullRoot, DateTime.UtcNow - olderThan); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + AppLog.Warn($"residual temporary cleanup failed: {ex.Message}"); + return 0; + } + } + + private static int CleanupResidualTempsInDirectory(string directory, DateTime cutoff) + { + int removed = 0; + try + { + foreach (string file in Directory.EnumerateFiles(directory)) + { + string name = Path.GetFileName(file); + bool ours = name.Contains(TempInfix, StringComparison.Ordinal) || + name.Contains(".restore-tmp-", StringComparison.Ordinal) || + name.Contains(".tmp-", StringComparison.Ordinal); + if (!ours || File.GetLastWriteTimeUtc(file) > cutoff) + { + continue; + } + try + { + File.Delete(file); + removed++; + } + catch + { + // Leave it; the next launch retries. + } + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + AppLog.Warn($"residual temporary cleanup could not list {directory}: {ex.Message}"); + } + try + { + foreach (string child in Directory.EnumerateDirectories(directory)) + { + removed += CleanupResidualTempsInDirectory(child, cutoff); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + AppLog.Warn($"residual temporary cleanup could not descend into {directory}: " + + ex.Message); + } + return removed; + } + + /// + /// Copy a file through the same flushed temporary and atomic move as a + /// durable write. Used for user-visible conflict copies, which must never be + /// left truncated after a crash. + /// + public static void Copy(string source, string destination) + { + if (!File.Exists(source)) + { + throw new FileNotFoundException("Source file is missing.", source); + } + Write(destination, File.ReadAllBytes(source)); + } + + /// + /// Write a brand-new file without ever overwriting: the flushed temporary + /// sibling is moved into place only when the target does not exist, so a + /// file created by another program in the meantime is not replaced. + /// + public static void WriteNew(string path, byte[] content) + { + WriteCore(path, content, overwrite: false); + } + + /// + /// Write small configuration/state files durably without creating a backup. + /// Uses the same flushed temporary file and atomic move as a database save. + /// + public static void Write(string path, byte[] content) + { + WriteCore(path, content, overwrite: true); + } + + private static void WriteCore(string path, byte[] content, bool overwrite) + { + if (content is null || content.Length == 0) + { + throw new ArgumentException("Refusing to write an empty file.", nameof(content)); + } + string fullPath = Path.GetFullPath(path); + string directory = Path.GetDirectoryName(fullPath)!; + Directory.CreateDirectory(directory); + string temp = Path.Combine(directory, + Path.GetFileName(fullPath) + TempInfix + Guid.NewGuid().ToString("N")); + try + { + using (var stream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, + FileShare.None, 4096, FileOptions.WriteThrough)) + { + stream.Write(content); + stream.Flush(flushToDisk: true); + } + if (overwrite) + { + File.Move(temp, fullPath, true); + } + else + { + // No overwrite flag: an existing target fails the move instead + // of being replaced. + File.Move(temp, fullPath); + } + } + finally + { + if (File.Exists(temp)) + { + try + { + File.Delete(temp); + } + catch + { + // The previous file is still intact; a clearly named + // temporary file is harmless. + } + } + } + } +} diff --git a/apps/windows/Keepassity.Core/BackupService.cs b/apps/windows/Keepassity.Core/BackupService.cs index 253438a..ef5bbae 100644 --- a/apps/windows/Keepassity.Core/BackupService.cs +++ b/apps/windows/Keepassity.Core/BackupService.cs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later using System.Globalization; -namespace Keepassity.Mock; +namespace Keepassity.Core; public sealed class BackupEntry { @@ -25,7 +25,7 @@ public static string BackupDirectory(string databasePath) } public static BackupEntry? CreateBackup(string databasePath, int retention = 20, - string? reason = null) + string? reason = null, DateTimeOffset? timestamp = null) { if (!File.Exists(databasePath)) { @@ -33,7 +33,9 @@ public static string BackupDirectory(string databasePath) } string directory = BackupDirectory(databasePath); Directory.CreateDirectory(directory); - string stamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss-fff", CultureInfo.InvariantCulture); + DateTimeOffset created = timestamp ?? DateTimeOffset.Now; + string stamp = created.ToLocalTime().ToString("yyyy-MM-dd_HH-mm-ss-fff", + CultureInfo.InvariantCulture); string name = reason is null ? $"{stamp}.kdbx" : $"{stamp}_{Sanitize(reason)}.kdbx"; string path = Path.Combine(directory, name); int suffix = 1; @@ -42,14 +44,47 @@ public static string BackupDirectory(string databasePath) path = Path.Combine(directory, Path.GetFileNameWithoutExtension(name) + $"-{suffix++}.kdbx"); } - File.Copy(databasePath, path); - Prune(directory, retention); + + // Copy to a temporary sibling, flush it, then move it into place. A crash + // during the copy therefore cannot leave a truncated file with a real + // backup name that a later restore might choose. + string temp = Path.Combine(directory, + $".{Path.GetFileName(path)}.tmp-{Guid.NewGuid():N}"); + try + { + File.Copy(databasePath, temp, overwrite: false); + FlushToDisk(temp); + File.Move(temp, path); + } + catch (IOException) when (File.Exists(path)) + { + // Another backup won the race for this name; pick the next suffix + // and copy again instead of overwriting it. + File.Delete(temp); + return CreateBackup(databasePath, retention, reason, timestamp); + } + finally + { + if (File.Exists(temp)) + { + try + { + File.Delete(temp); + } + catch + { + // A clearly named temporary file is safer than deleting the + // wrong path or leaving a partially named backup. + } + } + } + + Prune(directory, retention, path); return Describe(path); } public static List ListBackups(string databasePath) - { - string directory = BackupDirectory(databasePath); + { string directory = BackupDirectory(databasePath); if (!Directory.Exists(directory)) { return new List(); @@ -62,6 +97,47 @@ public static List ListBackups(string databasePath) .ToList(); } + /// + /// Removes temporary files a crash left inside the backup folder (a backup + /// interrupted mid-copy). Only names produced by this service are touched and + /// only when they are older than , so an active + /// backup is never disturbed. + /// + public static int CleanupResidualTemps(string databasePath, TimeSpan olderThan) + { + string directory = BackupDirectory(databasePath); + if (!Directory.Exists(directory)) + { + return 0; + } + DateTime cutoff = DateTime.UtcNow - olderThan; + int removed = 0; + try + { + foreach (string file in Directory.EnumerateFiles(directory, "*.tmp-*")) + { + try + { + if (File.GetLastWriteTimeUtc(file) > cutoff) + { + continue; + } + File.Delete(file); + removed++; + } + catch + { + // Leave it; the next unlock retries. + } + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + AppLog.Warn($"backup temporary cleanup failed: {ex.Message}"); + } + return removed; + } + /// Restore is two-step: back up the current file first, then replace it. public static void Restore(string databasePath, string backupPath, int retention = 20) { @@ -73,20 +149,52 @@ public static void Restore(string databasePath, string backupPath, int retention RestoreBytes(databasePath, content, retention); } - public static void RestoreBytes(string databasePath, byte[] content, int retention = 20) + public static void RestoreBytes(string databasePath, byte[] content, int retention = 20, + Func? changedBeforeReplace = null) { + if (content is null || content.Length == 0) + { + throw new ArgumentException("The backup contains no data.", nameof(content)); + } CreateBackup(databasePath, retention, "before-restore"); string directory = Path.GetDirectoryName(Path.GetFullPath(databasePath))!; + Directory.CreateDirectory(directory); string temp = Path.Combine(directory, $".{Path.GetFileName(databasePath)}.restore-tmp-{Guid.NewGuid():N}"); File.WriteAllBytes(temp, content); - if (File.Exists(databasePath)) + FlushToDisk(temp); + try { - File.Replace(temp, databasePath, databasePath + ".keepassity-restore-bak", true); + if (File.Exists(databasePath)) + { + if (changedBeforeReplace?.Invoke() == true) + { + throw new CoreException("VaultChanged", + "the database changed outside this window"); + } + // The pre-restore backup above is the recovery point; a second + // ".bak" file next to the database would only be clutter. + AtomicFile.ReplaceFlushedTemp(temp, databasePath); + } + else + { + File.Move(temp, databasePath); + } } - else + finally { - File.Move(temp, databasePath); + if (File.Exists(temp)) + { + try + { + File.Delete(temp); + } + catch + { + // The replacement already happened or a scanner holds the + // temporary file; the live database is what matters. + } + } } } @@ -98,7 +206,7 @@ public static void RestoreBytes(string databasePath, byte[] content, int retenti return new BackupEntry { Path = path, - Timestamp = info.LastWriteTime, + Timestamp = BackupTimestamp(path), Size = info.Length, }; } @@ -108,22 +216,51 @@ public static void RestoreBytes(string databasePath, byte[] content, int retenti } } - private static void Prune(string directory, int retention) + /// + /// Read the creation timestamp from the backup name instead of the file's + /// LastWriteTime. File.Copy preserves the source database's timestamp, so a + /// name is the only reliable ordering key across filesystems and clones. + /// + private static DateTimeOffset BackupTimestamp(string path) { - if (retention < 1) + string name = Path.GetFileNameWithoutExtension(path); + string stamp = name.Length >= 23 ? name[..23] : name; + if (DateTime.TryParseExact(stamp, "yyyy-MM-dd_HH-mm-ss-fff", + CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out DateTime local)) + { + return new DateTimeOffset(local); + } + try { - retention = 1; + return new FileInfo(path).LastWriteTime; } + catch + { + return DateTimeOffset.MinValue; + } + } + + private static void Prune(string directory, int retention, string keepPath) + { + retention = Math.Max(1, retention); + string fullKeep = Path.GetFullPath(keepPath); var files = Directory.EnumerateFiles(directory, "*.kdbx") - .Select(path => new FileInfo(path)) - .OrderByDescending(file => file.LastWriteTime) - .Skip(retention) + .Where(path => !string.Equals(Path.GetFullPath(path), fullKeep, + StringComparison.OrdinalIgnoreCase)) + .Select(path => new + { + Path = path, + Timestamp = BackupTimestamp(path), + }) + .OrderByDescending(file => file.Timestamp) + .ThenByDescending(file => Path.GetFileName(file.Path), StringComparer.Ordinal) + .Skip(retention - 1) .ToList(); - foreach (FileInfo file in files) + foreach (var file in files) { try { - file.Delete(); + File.Delete(file.Path); } catch { @@ -132,6 +269,13 @@ private static void Prune(string directory, int retention) } } + private static void FlushToDisk(string path) + { + using var stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, + FileShare.None, 4096, FileOptions.WriteThrough); + stream.Flush(flushToDisk: true); + } + private static string Sanitize(string value) { foreach (char invalid in Path.GetInvalidFileNameChars()) diff --git a/apps/windows/Keepassity.Core/CertificateTrust.cs b/apps/windows/Keepassity.Core/CertificateTrust.cs new file mode 100644 index 0000000..cb550d3 --- /dev/null +++ b/apps/windows/Keepassity.Core/CertificateTrust.cs @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Net.Security; + +namespace Keepassity.Core; + +/// What the shell should do about a WebDAV server certificate. +public enum CertificateTrustDecision +{ + /// The URL is not HTTPS, so no certificate is involved. + NotHttps, + /// A publicly trusted certificate; no prompt and no pinning. + PubliclyTrusted, + /// The presented fingerprint is already pinned for this endpoint. + AlreadyTrusted, + /// A self-signed endpoint seen for the first time; ask the user. + PromptFirstTime, + /// The endpoint is pinned but now presents a different certificate. + PromptChanged, +} + +/// +/// Pure certificate-trust decisions for WebDAV (SY-04: explicit per-endpoint +/// trust with a fingerprint, never a global validation bypass). The shell owns +/// the probe, the dialog and the settings write; the classification lives here +/// so it can be tested headless without a network (ADR-0035). +/// +public static class CertificateTrust +{ + /// Trust is pinned per endpoint (host and port), not per URL path, + /// so moving a database to another path on the same server keeps the pin. + public static string TrustKey(string url) + { + return Uri.TryCreate(url, UriKind.Absolute, out Uri? uri) + ? $"{uri.Host}:{uri.Port}" + : url; + } + + public static bool IsHttpsAbsolute(string url) + { + return Uri.TryCreate(url, UriKind.Absolute, out Uri? uri) && + uri.Scheme == Uri.UriSchemeHttps; + } + + /// + /// Classifies what to do with a probed certificate. A publicly trusted + /// certificate never needs a prompt; a pinned endpoint whose fingerprint + /// still matches is accepted silently; anything else is asked for, and a + /// pinned endpoint that changed is reported as a change so the dialog can + /// say so instead of pretending it is a first-time trust. + /// + public static CertificateTrustDecision Decide( + string url, + TlsCertificateInfo info, + IReadOnlyDictionary trustedCertificates) + { + if (!IsHttpsAbsolute(url)) + { + return CertificateTrustDecision.NotHttps; + } + if (info.IsPubliclyTrusted) + { + return CertificateTrustDecision.PubliclyTrusted; + } + string key = TrustKey(url); + if (trustedCertificates.TryGetValue(key, out string? trusted) && + string.Equals(trusted, info.Sha256FingerprintHex, StringComparison.Ordinal)) + { + return CertificateTrustDecision.AlreadyTrusted; + } + return trustedCertificates.ContainsKey(key) + ? CertificateTrustDecision.PromptChanged + : CertificateTrustDecision.PromptFirstTime; + } +} diff --git a/apps/windows/Keepassity.Core/CoreDtos.cs b/apps/windows/Keepassity.Core/CoreDtos.cs new file mode 100644 index 0000000..315ce7e --- /dev/null +++ b/apps/windows/Keepassity.Core/CoreDtos.cs @@ -0,0 +1,179 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Wire types for the keepassity FFI v1 JSON contract. They live in Core so the +// application-service layer (sync orchestration, backups) can depend on them +// without referencing the WinUI shell. +using System.Text.Json.Serialization; + +namespace Keepassity.Core; + +public sealed class GroupDto +{ + [JsonPropertyName("uuid")] public string Uuid { get; set; } = ""; + [JsonPropertyName("parent_uuid")] public string? ParentUuid { get; set; } + [JsonPropertyName("name")] public string Name { get; set; } = ""; + [JsonPropertyName("icon")] public int Icon { get; set; } + [JsonPropertyName("order")] public int Order { get; set; } +} + +public sealed class EntrySummaryDto +{ + [JsonPropertyName("uuid")] public string Uuid { get; set; } = ""; + [JsonPropertyName("title")] public string Title { get; set; } = ""; + [JsonPropertyName("username")] public string Username { get; set; } = ""; + [JsonPropertyName("url")] public string Url { get; set; } = ""; + [JsonPropertyName("group_uuid")] public string GroupUuid { get; set; } = ""; + [JsonPropertyName("has_totp")] public bool HasTotp { get; set; } + [JsonPropertyName("modified_unix")] public long ModifiedUnix { get; set; } +} + +public sealed class EntryFullDto +{ + [JsonPropertyName("uuid")] public string Uuid { get; set; } = ""; + [JsonPropertyName("group_uuid")] public string GroupUuid { get; set; } = ""; + [JsonPropertyName("title")] public string Title { get; set; } = ""; + [JsonPropertyName("username")] public string Username { get; set; } = ""; + [JsonPropertyName("password_secret")] public string PasswordSecret { get; set; } = ""; + [JsonPropertyName("url")] public string Url { get; set; } = ""; + [JsonPropertyName("notes")] public string Notes { get; set; } = ""; + [JsonPropertyName("tags")] public List Tags { get; set; } = new(); + [JsonPropertyName("custom_fields")] public List CustomFields { get; set; } = new(); + [JsonPropertyName("times")] public TimesDto Times { get; set; } = new(); + [JsonPropertyName("history_count")] public int HistoryCount { get; set; } + [JsonPropertyName("totp")] public TotpConfigDto? Totp { get; set; } +} + +public sealed class CustomFieldDto +{ + [JsonPropertyName("key")] public string Key { get; set; } = ""; + [JsonPropertyName("value")] public string Value { get; set; } = ""; + [JsonPropertyName("protected")] public bool Protected { get; set; } +} + +public sealed class TimesDto +{ + [JsonPropertyName("created_unix")] public long? CreatedUnix { get; set; } + [JsonPropertyName("modified_unix")] public long? ModifiedUnix { get; set; } +} + +public sealed class TotpConfigDto +{ + [JsonPropertyName("secret_base32")] public string SecretBase32 { get; set; } = ""; + [JsonPropertyName("issuer")] public string? Issuer { get; set; } + [JsonPropertyName("account")] public string? Account { get; set; } + [JsonPropertyName("algorithm")] public string Algorithm { get; set; } = "SHA1"; + [JsonPropertyName("digits")] public int Digits { get; set; } = 6; + [JsonPropertyName("period")] public int Period { get; set; } = 30; + [JsonPropertyName("encoder")] public string Encoder { get; set; } = "totp"; +} + +public sealed class TotpCodeDto +{ + [JsonPropertyName("code")] public string Code { get; set; } = ""; + [JsonPropertyName("remaining")] public int Remaining { get; set; } + [JsonPropertyName("period")] public int Period { get; set; } = 30; + [JsonPropertyName("digits")] public int Digits { get; set; } = 6; + [JsonPropertyName("algorithm")] public string Algorithm { get; set; } = "SHA1"; + [JsonPropertyName("issuer")] public string? Issuer { get; set; } + [JsonPropertyName("account")] public string? Account { get; set; } +} + +public sealed class PasswordGenerateDto +{ + [JsonPropertyName("password")] public string Password { get; set; } = ""; + [JsonPropertyName("entropy_bits")] public double EntropyBits { get; set; } +} + +public sealed class SearchResponseDto +{ + [JsonPropertyName("matches")] public List Matches { get; set; } = new(); +} + +public sealed class SearchMatchDto +{ + [JsonPropertyName("entry")] public EntrySummaryDto Entry { get; set; } = new(); + [JsonPropertyName("matched_fields")] public List MatchedFields { get; set; } = new(); +} + +public sealed class CreateEntryResponse +{ + [JsonPropertyName("uuid")] public string Uuid { get; set; } = ""; +} + +public sealed class CreateGroupResponse +{ + [JsonPropertyName("uuid")] public string Uuid { get; set; } = ""; +} + +public sealed class ErrorDto +{ + [JsonPropertyName("code")] public string? Code { get; set; } + [JsonPropertyName("message")] public string? Message { get; set; } +} + +public sealed class SyncDecisionDto +{ + [JsonPropertyName("action")] public string Action { get; set; } = ""; + [JsonPropertyName("reason")] public string Reason { get; set; } = ""; + [JsonPropertyName("degraded")] public bool Degraded { get; set; } + [JsonPropertyName("retry_after_ms")] public long? RetryAfterMs { get; set; } +} + +public sealed class SyncConflictDto +{ + [JsonPropertyName("uuid")] public string Uuid { get; set; } = ""; + [JsonPropertyName("kind")] public string Kind { get; set; } = ""; + [JsonPropertyName("local_modified_unix")] public long? LocalModifiedUnix { get; set; } + [JsonPropertyName("remote_modified_unix")] public long? RemoteModifiedUnix { get; set; } + [JsonPropertyName("fields")] public List Fields { get; set; } = new(); +} + +public sealed record SyncMergeResult(byte[] Bytes, List Conflicts); + +/// +/// The key-derivation settings a database header carries (read-only fact). +/// The insurance columns the UI shows ("strength", "compatibility") are derived +/// from these numbers, never stored here. +/// +public sealed class KdfInfoDto +{ + /// aes-kdf, argon2d or argon2id. + [JsonPropertyName("type")] public string Type { get; set; } = ""; + + [JsonPropertyName("rounds")] public ulong? Rounds { get; set; } + [JsonPropertyName("memory_kib")] public uint? MemoryKib { get; set; } + [JsonPropertyName("memory_mib")] public uint? MemoryMib { get; set; } + [JsonPropertyName("iterations")] public uint? Iterations { get; set; } + [JsonPropertyName("parallelism")] public uint? Parallelism { get; set; } + [JsonPropertyName("version")] public uint? Version { get; set; } + + /// + /// Whether mobile clients are expected to open this profile: AES-KDF needs no + /// extra memory, Argon2 at or below 64 MiB is the level they open. A fact + /// about other clients, not a recommendation. + /// + [JsonPropertyName("mobile_safe")] public bool MobileSafe { get; set; } +} + +/// Outer-header facts for the open database (database_info). +public sealed class DatabaseInfoDto +{ + [JsonPropertyName("format_version")] public string FormatVersion { get; set; } = ""; + + /// Root-group UUID: the stable identity of the database. + [JsonPropertyName("vault_uuid")] public string VaultUuid { get; set; } = ""; + + /// Database name as stored in the file. + [JsonPropertyName("name")] public string? Name { get; set; } + + [JsonPropertyName("cipher")] public string? Cipher { get; set; } + [JsonPropertyName("compression")] public string? Compression { get; set; } + [JsonPropertyName("kdf")] public KdfInfoDto? Kdf { get; set; } +} + +/// KDBX built-in settings the database settings page may edit. +public sealed class DatabaseSettingsDto +{ + [JsonPropertyName("recycle_bin_enabled")] public bool RecycleBinEnabled { get; set; } + [JsonPropertyName("history_max_items")] public long HistoryMaxItems { get; set; } + [JsonPropertyName("history_max_size")] public long HistoryMaxSize { get; set; } +} diff --git a/apps/windows/Keepassity.Core/CoreException.cs b/apps/windows/Keepassity.Core/CoreException.cs new file mode 100644 index 0000000..a03eb54 --- /dev/null +++ b/apps/windows/Keepassity.Core/CoreException.cs @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +namespace Keepassity.Core; + +/// +/// A failure reported by the native core. is the stable +/// contract code (for example BadPassword); the message is already +/// user-facing text and never contains vault content. +/// +public sealed class CoreException : Exception +{ + public CoreException(string code, string message) : base($"{code}: {message}") + { + Code = code; + } + + public string Code { get; } +} diff --git a/apps/windows/Keepassity.Core/CredentialStore.cs b/apps/windows/Keepassity.Core/CredentialStore.cs index 158a79c..1534952 100644 --- a/apps/windows/Keepassity.Core/CredentialStore.cs +++ b/apps/windows/Keepassity.Core/CredentialStore.cs @@ -3,7 +3,7 @@ using System.Security.Cryptography; using System.Text; -namespace Keepassity.Mock; +namespace Keepassity.Core; /// Stores WebDAV passwords encrypted with DPAPI for the current user. public sealed class CredentialStore @@ -12,7 +12,7 @@ public sealed class CredentialStore public CredentialStore() { - _directory = Path.Combine(AppDataPaths.Root, "credentials"); + _directory = Path.Combine(ApplicationPaths.Root, "credentials"); try { Directory.CreateDirectory(_directory); @@ -34,7 +34,7 @@ public void SavePassword(string url, string username, string password) } byte[] plain = Encoding.UTF8.GetBytes(password); byte[] encrypted = Protect(plain); - File.WriteAllBytes(PathFor(url, username), encrypted); + AtomicFile.Write(PathFor(url, username), encrypted); } public string? LoadPassword(string url, string username) @@ -44,13 +44,41 @@ public void SavePassword(string url, string username, string password) return null; } string path = PathFor(url, username); - if (!File.Exists(path)) + try + { + if (!File.Exists(path)) + { + return null; + } + byte[] encrypted = File.ReadAllBytes(path); + byte[] plain = Unprotect(encrypted); + return Encoding.UTF8.GetString(plain); + } + catch (Exception ex) when (ex is InvalidOperationException or IOException + or UnauthorizedAccessException + or System.Security.Cryptography.CryptographicException) { + // A credential blob encrypted for another user/machine, or a + // truncated file, must not break the settings/sync UI. Keep the + // bytes for diagnosis and behave as if no password were stored. + PreserveCorrupt(path); + AppLog.Warn($"stored WebDAV credential could not be read: {ex.Message}"); return null; } - byte[] encrypted = File.ReadAllBytes(path); - byte[] plain = Unprotect(encrypted); - return Encoding.UTF8.GetString(plain); + } + + private static void PreserveCorrupt(string path) + { + try + { + string backup = path + ".corrupt-" + DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + File.Move(path, backup, overwrite: false); + } + catch + { + // Leave the file in place if it cannot be moved; Load still returns + // null and the user can clear the credential explicitly. + } } /// diff --git a/apps/windows/Keepassity.Core/DiagnosticsService.cs b/apps/windows/Keepassity.Core/DiagnosticsService.cs index 1fb41e0..453669b 100644 --- a/apps/windows/Keepassity.Core/DiagnosticsService.cs +++ b/apps/windows/Keepassity.Core/DiagnosticsService.cs @@ -4,7 +4,7 @@ using System.Text; using System.Text.Json; -namespace Keepassity.Mock; +namespace Keepassity.Core; /// /// Builds a small diagnostics archive the user can inspect before sharing it. @@ -15,17 +15,26 @@ public static class DiagnosticsService { /// /// Builds the diagnostics archive on a worker thread; the UI calls this - /// without blocking while the logs are zipped. + /// without blocking while the logs are zipped. Older archives beyond the + /// newest are removed so repeated exports cannot + /// grow the data folder without bound. /// public static Task ExportAsync(AppSettings settings) - => Task.Run(() => ExportCore(settings)); + => Task.Run(() => ExportCore(settings, null, null)); - private static string ExportCore(AppSettings settings) + /// Archive retention: the newest exports are kept, older ones removed. + internal const int KeepArchives = 10; + + internal static string ExportCore(AppSettings settings, string? outputDirectory, + DateTimeOffset? now) { - string directory = Path.Combine(AppDataPaths.Root, "diagnostics"); + string directory = outputDirectory ?? + Path.Combine(ApplicationPaths.Root, "diagnostics"); Directory.CreateDirectory(directory); - string path = Path.Combine( - directory, $"keepassity-diagnostics-{DateTime.Now:yyyyMMdd-HHmmss}.zip"); + DateTimeOffset stampTime = now ?? DateTimeOffset.Now; + string stamp = stampTime.ToString("yyyyMMdd-HHmmss-fff", + System.Globalization.CultureInfo.InvariantCulture); + string path = UniqueArchivePath(directory, stamp); string temp = path + ".tmp"; if (File.Exists(temp)) { @@ -33,43 +42,113 @@ private static string ExportCore(AppSettings settings) } try { - using (var stream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write)) - using (var zip = new ZipArchive(stream, ZipArchiveMode.Create)) + using (var stream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, + FileShare.None, 4096, FileOptions.WriteThrough)) { - AddText(zip, "summary.txt", BuildSummary(settings)); - AddText(zip, "settings.json", BuildSettingsSnapshot(settings)); - foreach (string log in Directory - .EnumerateFiles(AppLog.DirectoryPath, "app-*.log") - .OrderByDescending(File.GetLastWriteTime) - .Take(3)) + // leaveOpen so the finished archive can be flushed to disk before + // the rename: a crash must not leave a truncated archive under a + // real diagnostics name. + using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, + leaveOpen: true)) { - AddFile(zip, "logs/" + Path.GetFileName(log), log); + AddText(zip, "summary.txt", BuildSummary(settings)); + AddText(zip, "settings.json", BuildSettingsSnapshot(settings)); + foreach (string log in Directory + .EnumerateFiles(AppLog.DirectoryPath, "app-*.log") + .OrderByDescending(File.GetLastWriteTime) + .Take(3)) + { + AddFile(zip, "logs/" + Path.GetFileName(log), log); + } } + stream.Flush(flushToDisk: true); } File.Move(temp, path); + Prune(directory); AppLog.Info("diagnostics exported"); return path; } catch { - if (File.Exists(temp)) + try + { + if (File.Exists(temp)) + { + File.Delete(temp); + } + } + catch { - File.Delete(temp); + // Best effort: the temporary name is clearly not an archive. } throw; } } + private static string UniqueArchivePath(string directory, string stamp) + { + string path = Path.Combine(directory, $"keepassity-diagnostics-{stamp}.zip"); + int suffix = 2; + while (File.Exists(path) || File.Exists(path + ".tmp")) + { + path = Path.Combine(directory, + $"keepassity-diagnostics-{stamp}-{suffix++}.zip"); + } + return path; + } + + private static void Prune(string directory) + { + try + { + // A crash-left temporary file has no value; remove it with the + // retention pass instead of leaving it forever. + foreach (string temp in Directory.EnumerateFiles(directory, "*.tmp")) + { + try + { + File.Delete(temp); + } + catch + { + // A file still being written by another export is kept. + } + } + var archives = Directory.EnumerateFiles(directory, + "keepassity-diagnostics-*.zip") + .Select(path => new FileInfo(path)) + .OrderByDescending(file => file.LastWriteTimeUtc) + .ThenByDescending(file => file.Name, StringComparer.Ordinal) + .Skip(KeepArchives) + .ToList(); + foreach (FileInfo archive in archives) + { + try + { + archive.Delete(); + } + catch + { + // Retention is best effort; the next export retries. + } + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + AppLog.Warn($"diagnostics retention failed: {ex.Message}"); + } + } + private static string BuildSummary(AppSettings settings) { var assembly = typeof(DiagnosticsService).Assembly; string version = assembly.GetCustomAttribute() ?.InformationalVersion ?? assembly.GetName().Version?.ToString() ?? "unknown"; - string syncStates = CountFiles(Path.Combine(AppDataPaths.Root, "state"), "*.json"); + string syncStates = CountFiles(Path.Combine(ApplicationPaths.Root, "state"), "*.json"); string credentials = CountFiles( - Path.Combine(AppDataPaths.Root, "credentials"), "*.bin"); + Path.Combine(ApplicationPaths.Root, "credentials"), "*.bin"); var summary = new StringBuilder() - .AppendLine("keepassity diagnostics") + .AppendLine("Keepassity diagnostics") .AppendLine($"app version: {version}") .AppendLine($"os: {Environment.OSVersion.VersionString}") .AppendLine($"process architecture: {System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture}") @@ -130,7 +209,10 @@ private static void AddFile(ZipArchive zip, string name, string path) { ZipArchiveEntry entry = zip.CreateEntry(name, CompressionLevel.Optimal); using Stream target = entry.Open(); - using FileStream source = File.OpenRead(path); + // The app may be appending to the newest log while diagnostics are + // exported; share read/write/delete instead of failing the export. + using var source = new FileStream(path, FileMode.Open, FileAccess.Read, + FileShare.ReadWrite | FileShare.Delete); source.CopyTo(target); } catch diff --git a/apps/windows/Keepassity.Core/ICoreClient.cs b/apps/windows/Keepassity.Core/ICoreClient.cs new file mode 100644 index 0000000..95712db --- /dev/null +++ b/apps/windows/Keepassity.Core/ICoreClient.cs @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +namespace Keepassity.Core; + +/// +/// The application-facing view of the native core. View models and application +/// services depend on this port, never on the P/Invoke implementation, so their +/// behaviour can be tested without the native library or a window. +/// +public interface ICoreClient : IDisposable +{ + /// Whether a database handle is currently held (also true when locked). + bool IsOpen { get; } + + /// Path of the database the handle was opened from, when known. + string? DatabasePath { get; } + + /// + /// Open and decrypt a database. Throws for a + /// wrong password, a damaged file or an unsupported format. + /// + Task OpenAsync(string path, string password); + + /// + /// Open and decrypt KDBX bytes already in memory, without reading a file + /// first. Used for a remote download so an unverified download never has to + /// reach the working copy; is only recorded + /// for diagnostics and later saves. + /// + Task OpenBytesAsync(byte[] kdbx, string password, string? databasePath = null); + + /// Lock the vault and drop the decrypted state; the handle stays usable. + Task LockAsync(); + + /// + /// Serialize the current model as KDBX bytes without writing them to disk. + /// The core has already decrypted and re-parsed the result before returning, + /// so the bytes are safe to place on disk. + /// + Task SaveBytesAsync(); + + /// + /// Decrypt and validate KDBX bytes with the given password without keeping a + /// handle. Used before downloaded or restored bytes replace the live file. + /// + Task VerifyAsync(byte[] bytes, string password); + + /// + /// Serialize the current model and write it durably. + /// is consulted once more after serialization; when it returns true nothing is + /// written and a with code VaultChanged is + /// thrown. + /// + Task SaveAsync(string path, int backupRetention = 20, + Func? databaseChanged = null); + + /// Ask the core's sync state machine what to do with the remote copy. + Task SyncDecideAsync(string remoteMetaJson, bool localDirty); + + /// Record the remote etag and content hash the local copy is now in sync with. + Task SyncCommitAsync(string? etag, string? sha256); + + /// + /// The encryption parameters the open file carries, read-only. Used to show + /// the facts about a database without deciding anything for the user. + /// + Task GetDatabaseInfoAsync(); + + /// + /// Change the KDF the next save writes, explicitly. + /// is one of keepass-classic, keepassxc, desktop or + /// strong; the core validates the values against the reader limits and + /// drops the cached transformed key. The change only reaches the disk with the + /// next (the app saves immediately after this call). + /// + Task SetKdfAsync(string preset); + + /// + /// Change the KDF to the exact values another file carried, for restoring the + /// parameters of an earlier copy that matches no named preset. Implementations + /// that only know the named presets may throw + /// ; the app's client supports the exact + /// form because the core accepts an explicit KDF object. + /// + Task SetKdfValuesAsync(KdfInfoDto kdf) + => throw new NotSupportedException( + "This core client only supports the named KDF presets."); + + /// The KDBX built-in settings (recycle bin, history limits). + Task GetDatabaseSettingsAsync() + => throw new NotSupportedException( + "This core client does not expose the database settings."); + + /// + /// Change the KDBX built-in settings; null fields stay as they are. The + /// change marks the model dirty and reaches the file on the next save. + /// + Task SetDatabaseSettingsAsync(bool? recycleBinEnabled, + long? historyMaxItems) + => throw new NotSupportedException( + "This core client does not expose the database settings."); +} diff --git a/apps/windows/Keepassity.Core/ISyncRemote.cs b/apps/windows/Keepassity.Core/ISyncRemote.cs new file mode 100644 index 0000000..0cbb5c3 --- /dev/null +++ b/apps/windows/Keepassity.Core/ISyncRemote.cs @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +namespace Keepassity.Core; + +/// +/// The remote side of a sync run: one KDBX file on a WebDAV server. The sync +/// coordinator depends on this narrow port, so its ordering and failure rules can +/// be tested without a network server. +/// +public interface ISyncRemote +{ + /// + /// Remote metadata, or null when the file does not exist yet (the first + /// upload creates it). + /// + Task GetMetadataAsync(CancellationToken cancellationToken = default); + + /// Download the remote file. The bytes are not trusted until verified. + Task DownloadAsync(CancellationToken cancellationToken = default); + + /// + /// Upload the bytes. is the remote etag the upload + /// is based on; null means "only create, never overwrite" (If-None-Match: *). + /// Throws with + /// when the server rejects the precondition (the remote changed meanwhile). + /// + Task UploadAsync(byte[] bytes, string? ifMatch, + CancellationToken cancellationToken = default); +} diff --git a/apps/windows/Keepassity.Core/IVaultDocument.cs b/apps/windows/Keepassity.Core/IVaultDocument.cs new file mode 100644 index 0000000..3a9cbd2 --- /dev/null +++ b/apps/windows/Keepassity.Core/IVaultDocument.cs @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +namespace Keepassity.Core; + +/// +/// The local side of a sync run: the currently open vault. The shell adapts its +/// window state to this port (durable write, core reopen, merge through a second +/// core handle), which keeps the sync coordinator platform-free and testable. +/// +public interface IVaultDocument +{ + /// Absolute path of the open database; also the sync-state key. + string Path { get; } + + /// Read the current bytes from disk. + Task ReadBytesAsync(); + + /// + /// Replace the live database with using the durable + /// save protocol. Must refuse (throw) when the file changed outside the + /// application since it was opened. + /// + Task ReplaceAsync(byte[] bytes); + + /// Reopen the core and refresh the UI from the bytes just written. + Task ReloadAsync(); + + /// + /// Three-way merge the remote bytes into the local model and return the + /// merged KDBX bytes plus the remaining conflicts. Never writes to disk. + /// + Task MergeRemoteAsync(byte[] remote); +} diff --git a/apps/windows/Keepassity.Core/KdfCommands.cs b/apps/windows/Keepassity.Core/KdfCommands.cs new file mode 100644 index 0000000..06fa88b --- /dev/null +++ b/apps/windows/Keepassity.Core/KdfCommands.cs @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Text.Json; + +namespace Keepassity.Core; + +/// +/// JSON payloads for the core's set_kdf command. +/// +/// They live in the platform-neutral assembly so the wire shape can be checked +/// without the shell or the native library: a typo here would otherwise only +/// show up as a failed call inside the running app. +/// +public static class KdfCommands +{ + /// Select one of the named presets (keepass-classic …). + public static string ForPreset(string preset) + { + ArgumentException.ThrowIfNullOrWhiteSpace(preset); + return JsonSerializer.Serialize(new + { + command = "set_kdf", + preset, + }); + } + + /// Apply exact values, used when restoring what an earlier copy carried. + public static string ForValues(KdfInfoDto kdf) + { + ArgumentNullException.ThrowIfNull(kdf); + ArgumentException.ThrowIfNullOrWhiteSpace(kdf.Type); + return JsonSerializer.Serialize(new + { + command = "set_kdf", + kdf = new + { + type = kdf.Type, + memory_mib = kdf.MemoryMib ?? (kdf.MemoryKib ?? 0) / 1024, + iterations = kdf.Iterations ?? 0, + parallelism = kdf.Parallelism ?? 0, + rounds = kdf.Rounds ?? 0, + }, + }); + } +} diff --git a/apps/windows/Keepassity.Core/Keepassity.Core.csproj b/apps/windows/Keepassity.Core/Keepassity.Core.csproj index bbe6b99..c800fd3 100644 --- a/apps/windows/Keepassity.Core/Keepassity.Core.csproj +++ b/apps/windows/Keepassity.Core/Keepassity.Core.csproj @@ -3,10 +3,20 @@ future Linux shell): paths, settings, sync state, WebDAV, backups and diagnostics. No WinUI or other UI dependency belongs here. --> - net8.0 + net10.0 enable enable - Keepassity.Mock + Keepassity.Core Keepassity.Core + + + + + + + + diff --git a/apps/windows/Keepassity.Core/Localization/LocalizationCatalog.cs b/apps/windows/Keepassity.Core/Localization/LocalizationCatalog.cs new file mode 100644 index 0000000..75ffb35 --- /dev/null +++ b/apps/windows/Keepassity.Core/Localization/LocalizationCatalog.cs @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Globalization; +using System.Text.Json; + +namespace Keepassity.Core; + +/// +/// Platform-neutral UI language catalog. +/// +/// The shells ship one JSON catalog per language under +/// Localization/<domain>.<language>.json (embedded in this +/// assembly). A catalog maps an English source string to its translation, so the +/// English UI needs no catalog at all: an untranslated key renders as the English +/// text instead of a raw key. Keeping this logic in the platform-neutral services +/// assembly (instead of WinUI/MRT resources) buys three things the single-window +/// shell needs: the language can change at runtime without recreating the window, +/// the many labels that are built in code-behind can use the same lookup, and the +/// catalog can be unit tested without a UI. +/// +/// The Windows shell wraps this class with Loc (event + attached +/// properties) and stores the user's choice in settings.json; see +/// docs/adr/ADR-0031-runtime-ui-localization.md for the trade-offs against +/// the x:Uid/Resources.resw approach. +/// +public sealed class LocalizationCatalog +{ + /// Settings value that follows the Windows display language. + public const string SystemLanguage = "system"; + public const string EnglishLanguage = "en"; + public const string ChineseLanguage = "zh-CN"; + + private const string ResourceInfix = ".Localization."; + private const string ChineseResourceSuffix = ".zh-CN.json"; + + private readonly Dictionary _translations; + + private LocalizationCatalog(string language, Dictionary translations, + IReadOnlyList duplicateKeys) + { + Language = language; + _translations = translations; + DuplicateKeys = duplicateKeys; + } + + /// Resolved language tag: en or zh-CN. + public string Language { get; } + + /// Translation count loaded for the active language (0 for English). + public int TranslationCount => _translations.Count; + + /// + /// Loaded key/value pairs. Exposed for diagnostics, the catalog completeness + /// gate and tests; callers must treat it as read-only. + /// + public IReadOnlyDictionary Translations => _translations; + + /// + /// Keys defined by more than one catalog file. A duplicate is a packaging bug; + /// the first definition wins and the shell logs the list once at startup. + /// + public IReadOnlyList DuplicateKeys { get; } + + /// Loads the catalog for a resolved language tag. + public static LocalizationCatalog Load(string language) + { + string normalized = NormalizeLanguage(language); + var translations = new Dictionary(StringComparer.Ordinal); + var duplicates = new List(); + if (normalized == ChineseLanguage) + { + foreach (string resource in ReadCatalogResourceNames()) + { + using Stream? stream = typeof(LocalizationCatalog).Assembly + .GetManifestResourceStream(resource); + if (stream is null) + { + continue; + } + using JsonDocument document = JsonDocument.Parse(stream); + if (document.RootElement.ValueKind != JsonValueKind.Object) + { + throw new InvalidDataException( + $"Language catalog {resource} must be a JSON object."); + } + foreach (JsonProperty property in document.RootElement.EnumerateObject()) + { + string key = property.Name; + string? value = property.Value.ValueKind == JsonValueKind.String + ? property.Value.GetString() + : null; + if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(value)) + { + continue; + } + if (!translations.TryAdd(key, value!)) + { + duplicates.Add(key); + } + } + } + } + return new LocalizationCatalog(normalized, translations, duplicates); + } + + /// + /// Resolves a stored setting (system, en, zh-CN, or an + /// arbitrary BCP-47 tag) to a language this build ships. Unknown tags fall back + /// to English; any Chinese variant uses the Simplified Chinese catalog. + /// + public static string NormalizeLanguage(string? setting) + { + string value = (setting ?? SystemLanguage).Trim(); + if (value.Length == 0) + { + return DetectSystemLanguage(); + } + if (value.Equals(SystemLanguage, StringComparison.OrdinalIgnoreCase)) + { + return DetectSystemLanguage(); + } + if (value.StartsWith("zh", StringComparison.OrdinalIgnoreCase)) + { + return ChineseLanguage; + } + return EnglishLanguage; + } + + /// Language implied by the current Windows display language. + public static string DetectSystemLanguage() + => CultureInfo.CurrentUICulture.TwoLetterISOLanguageName.Equals( + "zh", StringComparison.OrdinalIgnoreCase) + ? ChineseLanguage + : EnglishLanguage; + + /// True when the catalog defines a translation for the key. + public bool HasTranslation(string key) + => Language == ChineseLanguage && _translations.ContainsKey(key); + + /// + /// Returns the translation, or when the active + /// language has no entry. English always uses the fallback. + /// + public string Get(string key, string? fallback = null) + { + string resolvedFallback = fallback ?? key; + if (Language == ChineseLanguage && _translations.TryGetValue(key, out string? value)) + { + return value; + } + return resolvedFallback; + } + + /// Looks up a formatted string; placeholders use composite format syntax. + public string Format(string key, params object?[] arguments) + => string.Format(CultureInfo.InvariantCulture, Get(key), arguments); + + private static IEnumerable ReadCatalogResourceNames() + { + IEnumerable names = typeof(LocalizationCatalog).Assembly + .GetManifestResourceNames(); + return names + .Where(name => name.Contains(ResourceInfix, StringComparison.Ordinal)) + .Where(name => name.EndsWith(ChineseResourceSuffix, StringComparison.OrdinalIgnoreCase)) + .OrderBy(name => name, StringComparer.Ordinal); + } +} diff --git a/apps/windows/Keepassity.Core/Localization/ui.zh-CN.json b/apps/windows/Keepassity.Core/Localization/ui.zh-CN.json new file mode 100644 index 0000000..c69425b --- /dev/null +++ b/apps/windows/Keepassity.Core/Localization/ui.zh-CN.json @@ -0,0 +1,224 @@ +{ + "About": "关于", + "About.LicenseBody": "本程序是自由软件:你可以根据自由软件基金会发布的 GNU 通用公共许可证条款(第 3 版或你选择的任何更新版本)重新分发和/或修改它。本程序的分发是希望它有用,但不作任何担保,甚至不包含适销性或特定用途适用性的默示担保。详情请参阅 GNU 通用公共许可证;完整的许可证文本随源代码仓库中的 LICENSE 文件提供。", + "All entries": "全部条目", + "Appearance": "外观", + "Application settings": "应用设置", + "Backup copies to keep": "保留的备份份数", + "Backup folder": "备份文件夹", + "Backups": "备份", + "Cancel": "取消", + "Clear copied secrets after 30 seconds": "30 秒后清除已复制的机密内容", + "Configure WebDAV in Database settings first.": "请先在数据库设置里配置 WebDAV。", + "Conflict": "冲突", + "Copies the currently displayed one-time password": "复制当前显示的一次性密码", + "Copies the custom field value to the clipboard": "将自定义字段值复制到剪贴板", + "Copies the password to the clipboard": "将密码复制到剪贴板", + "Copies the username to the clipboard": "将用户名复制到剪贴板", + "Copies the website URL to the clipboard": "将网站链接复制到剪贴板", + "Copy": "复制", + "Copy custom field": "复制自定义字段", + "Copy one-time password": "复制一次性密码", + "Copy password": "复制密码", + "Copy username": "复制用户名", + "Copy website": "复制网站", + "Create new database": "新建数据库", + "Create the first entry with New.": "用“新建”创建第一个条目。", + "Custom fields": "自定义字段", + "Dark": "深色", + "Database navigation": "数据库导航", + "Database settings": "数据库设置", + "Delete": "删除", + "Delete entry": "删除条目", + "Details": "详细信息", + "Diagnostics export failed: {0}": "诊断信息导出失败:{0}", + "Diagnostics exported: {0}": "诊断信息已导出:{0}", + "Edit": "编辑", + "Edit entry": "编辑条目", + "English": "English", + "Entries": "条目", + "Entry details": "条目详情", + "Exit Keepassity": "退出 Keepassity", + "Export diagnostics": "导出诊断信息", + "Export diagnostics…": "导出诊断信息…", + "Export logs and settings (no secrets)": "导出日志和设置(不含机密信息)", + "GPL-3.0 license text": "GPL-3.0 许可证文本", + "Inactivity minutes before lock": "闲置多少分钟后锁定", + "Keepassity - {0}": "Keepassity - {0}", + "Keepassity - {0} ({1})": "Keepassity - {0}({1})", + "Keepassity {0} · local-first KeePass-compatible client": "Keepassity {0} · 本地优先的 KeePass 兼容客户端", + "Language": "语言", + "License: GNU General Public License, version 3 or later (GPL-3.0-or-later).": "许可证:GNU 通用公共许可证第 3 版或更新版本(GPL-3.0-or-later)。", + "Light": "浅色", + "Local changed": "本地已更改", + "Local files are read and written through the Keepassity core. Databases opened from WebDAV keep a local working copy and sync back on save.": "本地文件通过 Keepassity 核心读写。从 WebDAV 打开的数据库会保留本地工作副本,并在保存时同步回去。", + "Local only": "仅本地", + "Local working copy: {0}": "本地工作副本:{0}", + "Location": "位置", + "Lock": "锁定", + "Lock the vault after inactivity": "闲置后锁定密码库", + "Lock vault": "锁定密码库", + "Locks the vault immediately (Ctrl+L)": "立即锁定密码库(Ctrl+L)", + "Master password": "主密码", + "New": "新建", + "New database…": "新建数据库…", + "New entry": "新建条目", + "Nextcloud/ownCloud with two-factor authentication requires an app password. Server URL presets are offered when opening a database from WebDAV.": "启用两步验证的 Nextcloud/ownCloud 需要使用应用密码。从 WebDAV 打开数据库时会提供服务器地址预设。", + "No credentials": "缺少凭据", + "No database selected": "未选择数据库", + "No entries here": "这里没有条目", + "No entries with TOTP in this view. Clear the filter to see all entries.": "此视图中没有带 TOTP 的条目。清除筛选即可查看全部条目。", + "No stored password for this WebDAV target.": "此 WebDAV 目标未存储密码。", + "No stored password to clear.": "没有可清除的已存储密码。", + "Not synced": "未同步", + "Notes": "备注", + "Off": "关", + "Offline": "离线", + "On": "开", + "One-time password": "一次性密码", + "Open": "打开", + "Open a local .kdbx file or open from WebDAV": "打开本地 .kdbx 文件,或从 WebDAV 打开", + "Open a local .kdbx file, connect to WebDAV, or create a new database.": "打开本地 .kdbx 文件、连接 WebDAV,或新建数据库。", + "Open backup folder": "打开备份文件夹", + "Open database from WebDAV": "从 WebDAV 打开数据库", + "Open from WebDAV…": "从 WebDAV 打开…", + "Open local database file": "打开本地数据库文件", + "Open local file…": "打开本地文件…", + "Open or create a database": "打开或新建数据库", + "Open recent database {0}": "打开最近的数据库 {0}", + "Open the folder with timestamped database backups": "打开存放带时间戳数据库备份的文件夹", + "Open website": "打开网站", + "Opens the website in the default browser": "用默认浏览器打开网站", + "Password": "密码", + "Password stored for {0} (Windows DPAPI).": "已为 {0} 存储密码(Windows DPAPI)。", + "Recent databases": "最近的数据库", + "Remote repaired": "远程已修复", + "Remote unreadable": "远程无法打开", + "Remove from recent list": "从最近列表中移除", + "Resolving conflict": "正在解决冲突", + "Retrying sync in {0} ms": "{0} 毫秒后重试同步", + "Reveals the password in this panel": "在此面板中显示密码", + "Save": "保存", + "Search": "搜索", + "Search entries": "搜索条目", + "Search results": "搜索结果", + "Search the open database (Ctrl+F)": "搜索已打开的数据库(Ctrl+F)", + "Select an entry": "选择一个条目", + "Set the WebDAV password in Database settings.": "请在数据库设置里设置 WebDAV 密码。", + "Settings": "设置", + "Settings.WebDavNote": "地址必须指向 .kdbx 文件。WebDAV 密码使用 Windows DPAPI 存储,不会写入明文设置文件;清除它不会影响远程数据库。", + "Settings.WebDavSourceNote": "此数据库是从 WebDAV 打开的;本次会话中来源地址固定。若要切换来源,请锁定后使用解锁页面的“从 WebDAV 打开…”。WebDAV 密码使用 Windows DPAPI 存储,清除它不会影响远程数据库。", + "Show": "显示", + "Show Keepassity": "显示 Keepassity", + "Show password": "显示密码", + "Shows the last sync result; invokes a sync now": "显示上次同步结果;点击立即同步", + "Simplified Chinese": "简体中文", + "Sort and filter": "排序和筛选", + "Sort and filter entries": "排序和筛选条目", + "Source code": "源代码", + "Start minimized to the notification area": "启动时最小化到通知区域", + "Status": "状态", + "Status message": "状态消息", + "Stored WebDAV password cleared": "已清除存储的 WebDAV 密码", + "Sync after saving changes": "保存更改后同步", + "Sync error": "同步出错", + "Sync retry": "正在重试同步", + "Sync status": "同步状态", + "Sync status: {0}": "同步状态:{0}", + "Synced": "已同步", + "Synced (degraded)": "已同步(降级)", + "Syncing…": "正在同步…", + "TOTP only": "仅 TOTP", + "Tags": "标签", + "Toggle navigation": "切换导航", + "Unlock": "解锁", + "Unlock Keepassity": "解锁 Keepassity", + "Unlock database": "解锁数据库", + "Unlock status": "解锁状态", + "Unlocking database": "正在解锁数据库", + "Use system setting": "跟随系统设置", + "Use the system language": "使用系统语言", + "Username": "用户名", + "Vault": "密码库", + "WebDAV file URL": "WebDAV 文件地址", + "WebDAV needs https": "WebDAV 需要 https", + "WebDAV username": "WebDAV 用户名", + "WebDAV: {0}": "WebDAV:{0}", + "Website": "网站", + "locked": "已锁定", + "unlocked": "已解锁", + "{0} entries": "{0} 个条目", + "{0} entry": "{0} 个条目", + "{0} · {1} MiB · {2} iterations · {3} lanes": "{0} · {1} MiB · {2} 次 · {3} 路", + "AES-KDF · {0} rounds": "AES-KDF · {0} 轮", + "Change": "更改", + "Compatibility": "兼容性", + "Current parameters": "当前加密参数", + "Desktop only": "仅桌面", + "Encryption parameters": "加密参数", + "Encryption parameters changed": "加密参数已更新", + "Encryption parameters restored": "加密参数已恢复", + "No readable backup carries the old parameters.": "没有可读取的备份带有旧参数。", + "The saved copy uses custom parameters that are not one of the presets.": "保存前那份使用的是自定义参数,不在预设之列。", + "Use the saved parameters": "使用保存前的参数", + "Encryption strength": "加密强度", + "Match the KeePass 2.x default": "与 KeePass 2.x 默认一致", + "Match the KeePassXC default": "与 KeePassXC 默认一致", + "Medium": "中", + "Not reported by the file header": "文件头未提供", + "Preset": "档位", + "Strong": "强", + "Stronger": "更强", + "Unlock a database first.": "请先解锁数据库。", + "Very strong": "很强", + "Weak": "弱", + "Dialog.EncryptionChangeNote": "更改加密参数会用新参数重新加密整个数据库:先备份当前文件,写出后读回校验,成功后才替换数据库并同步。", + "Notice.EncryptionShared": "这个数据库通过 WebDAV 共享。它的加密参数需要比手机客户端通常能提供的内存更多,手机端可能打不开。参数可在「加密参数」里调整。", + "Encryption": "加密", + "Format": "格式", + "File size": "文件大小", + "Database UUID": "库 UUID", + "Save connection": "保存连接", + "Sync now": "立即同步", + "Save to database": "保存到数据库", + "Move deleted entries to the Recycle Bin": "删除的条目移入回收站", + "Old versions kept per entry": "每个条目保留的旧版本数", + "Connection saved": "连接已保存", + "Saved to the database": "已保存到数据库", + "This database has no WebDAV source.": "这个数据库没有 WebDAV 源。", + "Untitled database": "未命名数据库", + "Never synced": "从未同步", + "Last sync {0}": "上次同步 {0}", + "Not configured": "未配置", + "Leave blank to keep the stored password": "留空则保留已存储的密码", + "Uploads the new revision right after a save.": "保存后立即上传新版本。", + "Stored with Windows DPAPI on this computer only; it never travels with the database.": "只保存在这台电脑上(Windows DPAPI),不会随数据库同步。", + "What the file header carries. Changing them re-encrypts the whole database.": "这是文件头里记录的参数;更改会用新参数重新加密整个数据库。", + "Follow Windows or pin a theme.": "跟随 Windows,或固定使用浅色/深色。", + "Takes effect immediately.": "立即生效。", + "Passwords and codes disappear from the clipboard.": "密码和验证码会从剪贴板消失。", + "The master password is required again.": "需要重新输入主密码。", + "History stored inside the database, not next to it.": "历史记录保存在数据库内部,不产生额外文件。", + "Deleting an entry keeps it recoverable.": "删除的条目仍可找回。", + "Theme": "主题", + "Sync": "同步", + "Applies immediately": "立即生效", + "Needs saving": "需要保存", + "Rewrites the database file": "重写数据库文件", + "Local backups": "本机备份", + "How many previous copies of the file to keep on this computer. Saved immediately; never uploaded.": "每次保存前在本机保留的上一版副本份数;立即生效,不会上传。", + "WebDAV connection": "WebDAV 连接", + "The source is fixed when the database is opened; open it from WebDAV again to change it.": "数据库来源在打开时已固定;要更改请再次从 WebDAV 打开该库。", + "This database is local. There is no WebDAV connection to configure.": "此库保存在本机,没有 WebDAV 连接需要配置。", + "Encryption parameters decide how long opening takes and whether phone apps can read the file. Changing them rewrites the whole database and syncs it.": "加密参数决定打开耗时与手机 App 兼容性;更改会重写整个数据库并同步。", + "Change encryption parameters…": "更改加密参数…", + "Restore the saved parameters": "恢复已保存的参数", + "Entries and Recycle Bin": "条目与回收站", + "File information": "文件信息", + "Unsaved changes": "有未保存的更改", + "Security": "安全", + "Startup": "启动", + "Locking hides secrets and clears the clipboard; you will need the master password again.": "锁定后隐藏明文并清空剪贴板;重新打开需要主密码。", + "License text": "许可全文", + "Changes are saved as you make them unless a section says otherwise.": "改动会随手保存;需要保存的分区会标明。" +} diff --git a/apps/windows/Keepassity.Core/Localization/window.zh-CN.json b/apps/windows/Keepassity.Core/Localization/window.zh-CN.json new file mode 100644 index 0000000..4802492 --- /dev/null +++ b/apps/windows/Keepassity.Core/Localization/window.zh-CN.json @@ -0,0 +1,237 @@ +{ + "\"{0}\" and everything inside it will be moved to the Recycle Bin when it is enabled, otherwise deleted permanently. This cannot be undone.": "“{0}”及其中的全部内容将在回收站启用时移入回收站,否则将被永久删除。此操作无法撤销。", + "\"{0}\" is already at the top level — nothing to move.": "“{0}”已在顶层,无需移动。", + "\"{0}\" is already in {1} — nothing to move.": "“{0}”已在 {1} 中,无需移动。", + "\"{0}\" will be moved to the recycle bin.": "“{0}”将被移到回收站。", + "Algorithm": "算法", + "Already at the top level": "已在顶层", + "Already in {0}": "已在 {0} 中", + "At least one character class must stay enabled.": "必须至少保持一种字符类型启用。", + "Back": "返回", + "Backup": "备份", + "Backup folder: {0}": "备份文件夹:{0}", + "Backup restored": "备份已恢复", + "Backups: {0}": "备份:{0}", + "Base32 secret": "Base32 密钥", + "Browse…": "浏览…", + "Busy saving or syncing; the vault was not locked. Try again in a moment.": "正在保存或同步,密码库未锁定。请稍后重试。", + "Busy saving or syncing; try again in a moment.": "正在保存或同步,请稍后重试。", + "Cancel and keep both files untouched": "取消,保持两个文件不变", + "Cannot create database": "无法创建数据库", + "Cannot open database": "无法打开数据库", + "Cannot save settings: {0}": "无法保存设置:{0}", + "Cannot clear stored password: {0}": "无法清除已存储的密码:{0}", + "Changes are saved automatically; syncing now…": "更改会自动保存,正在同步…", + "Choose a .kdbx database first.": "请先选择一个 .kdbx 数据库。", + "Choose where to save the database.": "请选择数据库的保存位置。", + "Clipboard QR failed: {0}": "剪贴板二维码处理失败:{0}", + "Clipboard cleared": "剪贴板已清除", + "Close password generator": "关闭密码生成器", + "Confirm master password": "确认主密码", + "Copy TOTP": "复制 TOTP", + "Could not check the TLS certificate of {0}:{1}: {2}": "无法检查 {0}:{1} 的 TLS 证书:{2}", + "Could not read otpauth URI: {0}": "无法读取 otpauth URI:{0}", + "Create": "新建", + "Custom / paste a URL": "自定义 / 粘贴地址", + "Custom field copied": "自定义字段已复制", + "Database created": "数据库已创建", + "Database created on WebDAV": "已在 WebDAV 上创建数据库", + "Database file not found": "未找到数据库文件", + "Database is damaged": "数据库已损坏", + "Database name": "数据库名称", + "Database ready to unlock": "数据库已就绪,可以解锁", + "Delete entry?": "删除条目?", + "Delete group": "删除分组", + "Delete group and contents?": "删除分组及其内容?", + "Delete group?": "删除分组?", + "Dialog.CertificateChangedBody": "服务器证书在信任之后发生了变化。仅当你或管理员确认这是自己所做的更改时,才应继续。", + "Dialog.CertificateUntrustedBody": "Windows 不信任此服务器的证书。对于自签名证书而言这很正常;仅当你自己安装了该服务器,或管理员向你提供了此指纹时,才应信任它。", + "Dialog.ConflictBody": "本地和远程都已更改。在询问如何处理之前,已保存冲突副本。", + "Dialog.NewDatabaseBody": "创建一个带有 General 分组的空 KDBX 4.0 数据库。主密码不会被存储。", + "Dialog.NewDatabaseWebDavBody": "新数据库会先上传到此地址。已有的远程文件绝不会被覆盖。", + "Dialog.WebDavOpenBody": ".kdbx 文件会下载为加密的本地工作副本。保存时会同步回此地址;冲突绝不会静默覆盖。启用两步验证的 Nextcloud/ownCloud 账户需要使用应用密码,而不是账户密码。", + "Digits": "位数", + "Digits (0-9)": "数字 (0-9)", + "Done": "完成", + "Downloaded from WebDAV": "已从 WebDAV 下载", + "Downloaded remote changes": "已下载远程更改", + "Edit TOTP": "编辑 TOTP", + "Enter a database name.": "请输入数据库名称。", + "Enter a master password.": "请输入主密码。", + "Enter an absolute http(s) URL for the new database.": "请为新数据库输入一个绝对的 http(s) 地址。", + "Enter an https:// URL that points to the .kdbx file (Basic authentication requires TLS).": "请输入指向 .kdbx 文件的 https:// 地址(Basic 认证必须使用 TLS)。", + "Enter the WebDAV password (or use a URL whose credential is stored).": "请输入 WebDAV 密码(或使用已存储凭据的地址)。", + "Enter the WebDAV password.": "请输入 WebDAV 密码。", + "Enter the WebDAV username.": "请输入 WebDAV 用户名。", + "Enter the master password to unlock this database.": "请输入主密码以解锁此数据库。", + "Enter the master password to unlock. Saves will sync back to this file.": "请输入主密码以解锁。保存时会同步回此文件。", + "Enter the master password.": "请输入主密码。", + "Entropy: {0:F1} bits": "熵:{0:F1} 比特", + "Entropy: —": "熵:—", + "Entry created and saved": "条目已创建并保存", + "Entry moved to the recycle bin": "条目已移到回收站", + "Entry name": "条目名称", + "Entry updated and saved": "条目已更新并保存", + "Every change is saved automatically — nothing to save.": "所有更改都会自动保存,无需手动保存。", + "Exclude ambiguous characters (I l 1 O 0 o)": "排除易混淆字符 (I l 1 O 0 o)", + "Expires": "到期时间", + "Generate": "生成", + "Generate password": "生成密码", + "Generation failed: {0}": "生成失败:{0}", + "Generator.OptionsBody": "选项由核心生成器应用;密码会写入该字段,保存时会随条目一起存储。", + "Group": "分组", + "Group \"{0}\" created": "分组“{0}”已创建", + "Group deleted": "分组已删除", + "Group moved to the Recycle Bin": "分组已移入回收站", + "Group name": "分组名称", + "Group renamed": "分组已重命名", + "Import QR image…": "导入二维码图片…", + "Imported {0}. Review and save.": "已导入 {0}。请检查后保存。", + "Issuer": "颁发者", + "Keep both (recommended)": "两者都保留(推荐)", + "Keep local": "保留本地", + "Keep remote": "保留远程", + "Kept both versions; merged and uploaded ({0}).": "已保留两个版本;合并后已上传({0})。", + "Kept local version; remote copy was saved.": "已保留本地版本;远程副本已保存。", + "Kept remote version; local copy was saved.": "已保留远程版本;本地副本已保存。", + "Leave blank to use the stored password": "留空则使用已存储的密码", + "Leave the secret empty and save to remove TOTP.": "将密钥留空并保存即可移除 TOTP。", + "Length": "长度", + "Local copy: {0}": "本地副本:{0}", + "Local file": "本地文件", + "Lock failed: {0}": "锁定失败:{0}", + "Lowercase (a-z)": "小写字母 (a-z)", + "Merged": "已合并", + "Merged remote changes automatically ({0}).": "已自动合并远程更改({0})。", + "Move": "移动", + "Move entry": "移动条目", + "Move to": "移动到", + "Move to the top level": "移动到顶层", + "Move to {0}": "移动到 {0}", + "Moved to {0}": "已移动到 {0}", + "New database": "新建数据库", + "New entry here": "在此新建条目", + "New group": "新建分组", + "New group…": "新建分组…", + "No TOTP configured": "未配置 TOTP", + "No TOTP configured for this entry.": "此条目未配置 TOTP。", + "No TOTP yet. Paste or import a Base32 secret to add one.": "尚未配置 TOTP。粘贴或导入 Base32 密钥即可添加。", + "No backup opens with this master password.": "没有可用此主密码打开的备份。", + "No backups yet. They are created before each save.": "尚无备份。每次保存前都会创建备份。", + "No otpauth QR code found. Paste a Base32 secret instead.": "未找到 otpauth 二维码。请改为粘贴 Base32 密钥。", + "One-time code copied": "一次性密码已复制", + "Only .kdbx database files can be opened this way.": "只能通过此方式打开 .kdbx 数据库文件。", + "Only entries with TOTP": "仅显示带 TOTP 的条目", + "Open database": "打开数据库", + "Open from WebDAV": "从 WebDAV 打开数据库", + "Opening the local working copy. Changes will sync when the network is back.": "正在打开本地工作副本。网络恢复后更改将会同步。", + "Opens the password generator options": "打开密码生成器选项", + "Password copied": "密码已复制", + "Password generated. Save the entry to keep it.": "密码已生成。保存条目以保留该密码。", + "Password length": "密码长度", + "Paste QR / otpauth…": "粘贴二维码 / otpauth…", + "Period (seconds)": "周期(秒)", + "Previous session ended unexpectedly": "上次会话异常结束", + + "If the database looks wrong, check the newest backup.": "如果数据库内容有异常,请查看最新备份。", + "QR image failed: {0}": "二维码图片处理失败:{0}", + "QR imported. Review the parameters and save.": "二维码已导入。请检查参数后保存。", + "Refreshes in {0}s": "{0} 秒后刷新", + "Regenerate": "重新生成", + "Regenerate password": "重新生成密码", + "Remember password with Windows DPAPI": "使用 Windows DPAPI 记住密码", + "Remote changed again while repairing; will retry next sync.": "修复期间远程再次更改;将在下次同步时重试。", + "Remote changed again; local version kept, will retry next sync.": "远程再次更改;已保留本地版本,将在下次同步时重试。", + "Remote changed again; merged locally, will retry next sync.": "远程再次更改;已在本地合并,将在下次同步时重试。", + "Remote copy: {0}": "远程副本:{0}", + "Remote database unreadable": "远程数据库无法打开", + "Remove": "移除", + "Rename": "重命名", + "Rename group": "重命名分组", + "Rename group…": "重命名分组…", + "Replace remote with local copy": "用本地副本替换远程副本", + "Restore": "恢复", + "Restore backup": "恢复备份", + "Restore failed: {0}": "恢复失败:{0}", + "Restoring backs up the current database first. Keeping {0} copies.": "恢复前会先备份当前数据库。将保留 {0} 份副本。", + "SHA-256 fingerprint": "SHA-256 指纹", + "Save as": "保存为", + "Save failed: {0}": "保存失败:{0}", + "Save to": "保存位置", + "Saved": "已保存", + "Select at least one character class.": "请至少选择一种字符类型。", + "Server": "服务器", + "Server certificate changed": "服务器证书已更改", + "Server preset": "服务器预设", + "Set up TOTP": "设置 TOTP", + "Sort by group": "按分组排序", + "Sort by recently modified": "按最近修改排序", + "Sort by title": "按标题排序", + "Still running in the notification area. Use its menu to exit.": "仍在通知区域运行。请使用其菜单退出。", + "Subject": "使用者", + "Symbols (!@#$…)": "符号 (!@#$…)", + "Sync conflict": "同步冲突", + "Sync failed: {0}": "同步失败:{0}", + "Sync needs baseline": "同步基线不完整,请重新同步。", + "Sync paused. Local and remote are unchanged; conflict copies were saved.": "同步已暂停。本地和远程均未更改,冲突副本已保存。", + "Sync skipped: {0}": "已跳过同步:{0}", + "TOTP code unavailable": "TOTP 验证码暂时不可用", + "TOTP removed": "TOTP 已移除", + "TOTP saved": "TOTP 已保存", + "Tags (comma-separated)": "标签(逗号分隔)", + "That database is already open.": "该数据库已经打开。", + "That file already exists. Choose another path.": "该文件已存在。请选择其他路径。", + "The certificate presented by {0} was not trusted, so the connection was cancelled.": "{0} 提供的证书不受信任,因此连接已取消。", + "The database file no longer exists.": "数据库文件已不存在。", + "The database path is not valid.": "数据库路径无效。", + "The database is open in another Keepassity window. Close it there first.": "数据库已在另一个 Keepassity 窗口中打开。请先关闭那个窗口。", + "The database could not be opened. Restore the newest backup that opens with this master password? The damaged file is kept as a backup.": "无法打开数据库。要恢复可用此主密码打开的最新备份吗?损坏的文件会保留为备份。", + "The database was changed outside Keepassity. Reopen it before saving; nothing was overwritten.": "数据库已被 Keepassity 之外的程序修改。请重新打开后再保存;本次未覆盖任何内容。", + "The dropped file could not be read.": "无法读取拖入的文件。", + "The empty group \"{0}\" will be removed.": "空分组“{0}”将被移除。", + "The entry": "该条目", + "The file name must end in .kdbx.": "文件名必须以 .kdbx 结尾。", + "The master passwords do not match.": "两次输入的主密码不一致。", + "The remote copy was unreadable; it has been replaced with the local copy (saved as {0}).": "远程副本无法打开;已用本地副本替换(原文件已保存为 {0})。", + "The remote copy was unreadable; it has been replaced with the local copy.": "远程副本无法打开;已用本地副本替换。", + "The remote database cannot be opened with the current password. It may be corrupt, or it may be a valid database protected by a different master password from another device. Replace it with the local copy? The unreadable remote file will be overwritten (a local copy of it is kept).": "无法用当前密码打开远程数据库。它可能已损坏,也可能是另一设备用不同主密码保护的有效数据库。是否用本地副本替换?无法打开的远程文件将被覆盖(其本地副本会保留)。", + "The remote database cannot be opened with this password; the local copy was kept and the unreadable remote was saved as {0}.": "无法用该密码打开远程数据库;已保留本地副本,无法打开的远程文件已保存为 {0}。", + "The remote database cannot be opened with this password; the local copy was kept.": "无法用该密码打开远程数据库;已保留本地副本。", + "The remote database file was not found. Check the WebDAV file URL.": "未找到远程数据库文件。请检查 WebDAV 文件地址。", + "The remote file already exists. Choose another URL or open it from WebDAV.": "远程文件已存在。请选择其他地址,或从 WebDAV 打开它。", + "The vault is locked; sync cannot replace it.": "密码库已锁定,同步无法替换密码库文件。", + "The vault changed while syncing; the sync paused and nothing was overwritten.": "同步期间密码库发生更改,已暂停同步,未覆盖任何内容。", + "Title": "标题", + "Top level (no folder)": "顶层(无文件夹)", + "Trust": "信任", + "Trust this server certificate?": "信任此服务器证书?", + "URL copied": "网站地址已复制", + "Unlock failed: {0}": "解锁失败:{0}", + "Unlock the vault before generating a password.": "请先解锁密码库,再生成密码。", + "Unlock the vault before restoring a backup.": "请先解锁密码库,再恢复备份。", + "Unlock.DatabaseMissingBody": "数据库文件已不在该路径。它可能被移动了,或所在驱动器未连接。请使用“打开本地文件…”重新定位。", + "Unlock.FailureHintBody": "如果数据库无法打开,请导出诊断信息(仅包含日志和设置,不含密码库内容或密码),并随问题报告一并保留。每次保存前都会创建带时间戳的备份;最新的备份可从下方备份文件夹恢复。", + "Unlock.UnsyncedChangesBody": "本地工作副本中有尚未上传的更改。现在将打开它;解锁后会处理冲突。", + "Unsupported database": "不支持的数据库", + "Unsynced local changes": "存在未同步的本地更改", + "Untitled entry": "未命名条目", + "Uppercase (A-Z)": "大写字母 (A-Z)", + "Username copied": "用户名已复制", + "Vault is still saving. Lock again in a moment.": "密码库仍在保存,请稍后再锁定。", + "Vault locked": "密码库已锁定", + "Vault unlocked": "密码库已解锁", + "WebDAV is unreachable; working offline.": "无法连接 WebDAV,正在离线工作。", + "WebDAV password": "WebDAV 密码", + "WebDAV sync requires an https:// URL: Basic authentication must use TLS.": "WebDAV 同步需要 https:// 地址:Basic 认证必须使用 TLS。", + "WebDAV unreachable": "无法连接 WebDAV", + "Website copied": "网站已复制", + "Wrong master password": "主密码错误", + "entry changed on both sides": "条目在双方都已更改", + "local: {0}; remote: {1}": "本地:{0};远程:{1}", + "the group": "该分组", + "the top level": "顶层", + "{0} dialog": "{0}对话框", + "{0} panel": "{0}面板", + "{0} — clears in 30 seconds": "{0} — 30 秒后清除", + "{0}: {1}": "{0}:{1}" +} diff --git a/apps/windows/Keepassity.Core/LogFile.cs b/apps/windows/Keepassity.Core/LogFile.cs new file mode 100644 index 0000000..25a83a4 --- /dev/null +++ b/apps/windows/Keepassity.Core/LogFile.cs @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Text; + +namespace Keepassity.Core; + +/// +/// One directory of daily log files. Appends are bounded: a day file that grows +/// past the size cap is rotated to a single .1 sibling, and pruning keeps +/// both the retention window and a total-size ceiling. File handles share +/// read/write/delete so a second instance and the diagnostics exporter never lose +/// a write to a sharing violation. +/// +internal sealed class LogFile +{ + internal const long DefaultMaxFileBytes = 5 * 1024 * 1024; + internal const long DefaultMaxTotalBytes = 50 * 1024 * 1024; + + private readonly string _directory; + private readonly long _maxFileBytes; + private readonly object _gate = new(); + + public LogFile(string directory, long maxFileBytes = DefaultMaxFileBytes) + { + _directory = directory ?? throw new ArgumentNullException(nameof(directory)); + _maxFileBytes = maxFileBytes > 0 + ? maxFileBytes + : throw new ArgumentOutOfRangeException(nameof(maxFileBytes)); + } + + public void Append(string line, DateTimeOffset now) + { + lock (_gate) + { + Directory.CreateDirectory(_directory); + string path = Path.Combine(_directory, $"app-{now:yyyyMMdd}.log"); + try + { + if (File.Exists(path) && new FileInfo(path).Length >= _maxFileBytes) + { + // Keep exactly one rotated sibling; a crash-loop or an error + // loop therefore cannot grow the folder without bound. + File.Move(path, path + ".1", overwrite: true); + } + } + catch + { + // Rotation is best effort; the append below still records the line. + } + using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, + FileShare.ReadWrite | FileShare.Delete); + using var writer = new StreamWriter(stream, new UTF8Encoding(false)); + writer.Write(line); + writer.Write(Environment.NewLine); + } + } + + /// + /// Delete logs older than and then the oldest + /// remaining ones until the folder fits . + /// Returns the number of files removed. + /// + public int Prune(DateTimeOffset now, int retentionDays = 14, + long maxTotalBytes = DefaultMaxTotalBytes) + { + int removed = 0; + try + { + Directory.CreateDirectory(_directory); + DateTime cutoff = now.AddDays(-retentionDays).UtcDateTime; + List files = Enumerate(); + foreach (FileInfo file in files) + { + if (file.LastWriteTimeUtc >= cutoff) + { + continue; + } + if (TryDelete(file)) + { + removed++; + } + } + + files = Enumerate(); + long total = files.Sum(file => file.Length); + foreach (FileInfo file in files.OrderBy(file => file.LastWriteTimeUtc)) + { + if (total <= maxTotalBytes) + { + break; + } + long length = file.Length; + if (TryDelete(file)) + { + total -= length; + removed++; + } + } + } + catch + { + // Logging must never break the application. + } + return removed; + } + + private List Enumerate() + { + var files = new List(); + files.AddRange(Directory.EnumerateFiles(_directory, "app-*.log") + .Select(path => new FileInfo(path))); + files.AddRange(Directory.EnumerateFiles(_directory, "app-*.log.1") + .Select(path => new FileInfo(path))); + return files; + } + + private static bool TryDelete(FileInfo file) + { + try + { + file.Delete(); + return true; + } + catch + { + return false; + } + } +} diff --git a/apps/windows/Keepassity.Core/NewDatabasePreparer.cs b/apps/windows/Keepassity.Core/NewDatabasePreparer.cs new file mode 100644 index 0000000..66cfe06 --- /dev/null +++ b/apps/windows/Keepassity.Core/NewDatabasePreparer.cs @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Security.Cryptography; + +namespace Keepassity.Core; + +/// +/// Writes a freshly created database to disk with the same durability rules as a +/// save. For WebDAV it also claims the local working copy and records the clean +/// sync baseline, because the remote create-only upload has already succeeded by +/// then; a plain copy or a half-written local file must not be able to hide that. +/// +public sealed class NewDatabasePreparer +{ + private readonly SyncStateStore _states; + + public NewDatabasePreparer(SyncStateStore states) + { + _states = states ?? throw new ArgumentNullException(nameof(states)); + } + + /// + /// Durably write a new local database. Existing files are never replaced: + /// the create-only move fails instead, so a program that created the same + /// path between the caller's check and this write keeps its data. + /// + public void CreateLocal(string path, byte[] bytes) + { + RequireContent(bytes); + AtomicFile.WriteNew(path, bytes); + } + + /// + /// After a successful create-only upload: durably write the local working + /// copy (backing up a stale copy if one exists), then record the clean sync + /// baseline. The order means a crash in between leaves the vault dirty + /// instead of silently claiming a baseline that the local file never had. + /// Returns the working-copy path. + /// + public async Task CommitRemoteAsync(string url, string username, byte[] bytes, + string? etag, int backupRetention = 20, CancellationToken cancellationToken = default) + { + RequireContent(bytes); + string normalizedUrl = url.Trim(); + string normalizedUsername = username.Trim(); + string workingCopy = RemoteDatabaseStore.PathFor(normalizedUrl, normalizedUsername); + await Task.Run( + () => AtomicFile.Replace(workingCopy, bytes, backupRetention, "new database"), + cancellationToken).ConfigureAwait(false); + SyncState state = _states.Load(normalizedUrl, normalizedUsername, workingCopy); + state.Etag = etag; + state.Sha256 = Sha256Hex(bytes); + state.Size = bytes.Length; + state.RemoteModifiedUnix = null; + state.LocalDirty = false; + state.LastSyncUnix = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + _states.Save(normalizedUrl, normalizedUsername, workingCopy, state); + RemoteDatabaseStore.WriteMetadata(normalizedUrl, normalizedUsername); + return workingCopy; + } + + private static void RequireContent(byte[] bytes) + { + if (bytes is null || bytes.Length == 0) + { + throw new ArgumentException("The new database is empty.", nameof(bytes)); + } + } + + private static string Sha256Hex(byte[] bytes) + => Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(); +} diff --git a/apps/windows/Keepassity.Mock/RecentDatabaseStore.cs b/apps/windows/Keepassity.Core/RecentDatabaseStore.cs similarity index 75% rename from apps/windows/Keepassity.Mock/RecentDatabaseStore.cs rename to apps/windows/Keepassity.Core/RecentDatabaseStore.cs index 46abdc1..978c237 100644 --- a/apps/windows/Keepassity.Mock/RecentDatabaseStore.cs +++ b/apps/windows/Keepassity.Core/RecentDatabaseStore.cs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later using System.Text.Json; -namespace Keepassity.Mock; +namespace Keepassity.Core; public sealed class RecentDatabaseEntry { @@ -40,9 +40,15 @@ public sealed class RecentDatabaseStore private readonly string _filePath; private readonly List _entries = new(); - public RecentDatabaseStore() + /// + /// is for tests and diagnostics; the app uses the + /// application data root. + /// + public RecentDatabaseStore(string? path = null) { - _filePath = Path.Combine(AppDataPaths.Root, "recent-databases.json"); + _filePath = string.IsNullOrWhiteSpace(path) + ? System.IO.Path.Combine(ApplicationPaths.Root, "recent-databases.json") + : System.IO.Path.GetFullPath(path); Load(); } @@ -100,6 +106,7 @@ private void Load() List>(File.ReadAllText(_filePath), Options); if (loaded is null) { + PreserveCorruptFile(); return; } foreach (RecentDatabaseEntry entry in loaded) @@ -118,7 +125,9 @@ private void Load() } catch { - // A corrupt recent list must never block unlocking; start empty. + // A corrupt recent list must never block unlocking; start empty but + // keep the bytes so the failure can be diagnosed. + PreserveCorruptFile(); } } @@ -126,9 +135,7 @@ private void Save() { try { - string temp = _filePath + ".tmp"; - File.WriteAllText(temp, JsonSerializer.Serialize(_entries, Options)); - File.Move(temp, _filePath, true); + AtomicFile.Write(_filePath, JsonSerializer.SerializeToUtf8Bytes(_entries, Options)); } catch { @@ -136,11 +143,30 @@ private void Save() } } + private void PreserveCorruptFile() + { + try + { + if (!File.Exists(_filePath)) + { + return; + } + string backup = _filePath + ".corrupt-" + + DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + File.Copy(_filePath, backup, overwrite: false); + AppLog.Warn($"preserved unreadable recent-database list as {System.IO.Path.GetFileName(backup)}"); + } + catch + { + // Diagnostics must not block unlocking. + } + } + private static string Normalize(string path) { try { - return Path.GetFullPath(path); + return System.IO.Path.GetFullPath(path); } catch { diff --git a/apps/windows/Keepassity.Core/RemoteCacheCleaner.cs b/apps/windows/Keepassity.Core/RemoteCacheCleaner.cs new file mode 100644 index 0000000..c1355ce --- /dev/null +++ b/apps/windows/Keepassity.Core/RemoteCacheCleaner.cs @@ -0,0 +1,186 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Security.Cryptography; + +namespace Keepassity.Core; + +/// What a cache cleanup pass removed and why it kept the rest. +public sealed record RemoteCacheCleanupResult( + int RemovedWorkingCopies, + int RemovedOrphans, + int KeptDirty, + int KeptRecent, + int KeptUnknown) +{ + public int TotalRemoved => RemovedWorkingCopies + RemovedOrphans; + + public override string ToString() + => $"removed {TotalRemoved} (copies {RemovedWorkingCopies}, orphans {RemovedOrphans}); " + + $"kept dirty={KeptDirty}, recent={KeptRecent}, unknown={KeptUnknown}"; +} + +/// +/// Bounded-size cleanup for the local WebDAV cache. A clean working copy can be +/// downloaded again, so it may be dropped after it has not been touched for a +/// while; a copy with unsynced edits exists only on this machine and must never +/// be removed. Copies whose remote source is unknown (created before the +/// metadata sidecar existed) are kept too. +/// +public sealed class RemoteCacheCleaner +{ + private readonly SyncStateStore _states; + private readonly RecentDatabaseStore? _recents; + private readonly Func _now; + + public RemoteCacheCleaner(SyncStateStore states, Func? now = null, + RecentDatabaseStore? recents = null) + { + _states = states ?? throw new ArgumentNullException(nameof(states)); + _now = now ?? (() => DateTimeOffset.UtcNow); + _recents = recents; + } + + /// + /// Remove cached working copies that are clean (the file hash matches the + /// recorded baseline and there are no unsynced edits) and untouched for + /// , plus leftovers whose working copy is already + /// gone. Call only when no other instance may have a cache file open. + /// + public RemoteCacheCleanupResult Prune(IReadOnlyCollection keepPaths, + TimeSpan maxAge) + { + ArgumentNullException.ThrowIfNull(keepPaths); + var keep = new HashSet(keepPaths.Select(Path.GetFullPath), + StringComparer.OrdinalIgnoreCase); + string root = RemoteDatabaseStore.Root; + if (!Directory.Exists(root)) + { + return new RemoteCacheCleanupResult(0, 0, 0, 0, 0); + } + DateTimeOffset now = _now(); + int removed = 0; + int orphans = 0; + int keptDirty = 0; + int keptRecent = 0; + int keptUnknown = 0; + + foreach (string file in Directory.EnumerateFiles(root, "*.kdbx")) + { + string path = Path.GetFullPath(file); + if (keep.Contains(path)) + { + continue; + } + RemoteSourceMetadata? metadata = RemoteDatabaseStore.ReadMetadata(path); + if (metadata is null) + { + keptUnknown++; + continue; + } + byte[] bytes; + try + { + bytes = File.ReadAllBytes(path); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + keptUnknown++; + continue; + } + SyncState state = _states.Load(metadata.Url, metadata.Username, path); + bool clean = !state.LocalDirty && state.Sha256 is not null && + string.Equals(state.Sha256, Sha256Hex(bytes), + StringComparison.OrdinalIgnoreCase); + if (!clean) + { + keptDirty++; + continue; + } + if (now - File.GetLastWriteTimeUtc(path) < maxAge) + { + keptRecent++; + continue; + } + if (DeleteWorkingCopy(path, metadata)) + { + removed++; + } + else + { + keptUnknown++; + } + } + + string backupRoot = Path.Combine(root, ".keepassity", "backups"); + if (Directory.Exists(backupRoot)) + { + foreach (string directory in Directory.EnumerateDirectories(backupRoot)) + { + string workingCopy = Path.Combine(root, Path.GetFileName(directory)); + if (File.Exists(workingCopy) || keep.Contains(Path.GetFullPath(workingCopy))) + { + continue; + } + try + { + Directory.Delete(directory, recursive: true); + _recents?.Remove(workingCopy); + orphans++; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + AppLog.Warn($"orphaned remote backup could not be removed: {ex.Message}"); + } + } + } + + foreach (string metadataFile in Directory.EnumerateFiles(root, "*.source.json")) + { + string workingCopy = Path.Combine(root, + Path.GetFileName(metadataFile)[..^".source.json".Length] + ".kdbx"); + if (File.Exists(workingCopy) || keep.Contains(Path.GetFullPath(workingCopy))) + { + continue; + } + try + { + File.Delete(metadataFile); + _recents?.Remove(workingCopy); + orphans++; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + AppLog.Warn($"orphaned remote metadata could not be removed: {ex.Message}"); + } + } + + return new RemoteCacheCleanupResult(removed, orphans, keptDirty, keptRecent, + keptUnknown); + } + + private bool DeleteWorkingCopy(string path, RemoteSourceMetadata metadata) + { + try + { + // Delete the copy itself first: if it is unexpectedly held, nothing + // else is removed and the entry simply stays cached. + File.Delete(path); + string backupDirectory = BackupService.BackupDirectory(path); + if (Directory.Exists(backupDirectory)) + { + Directory.Delete(backupDirectory, recursive: true); + } + _states.Remove(metadata.Url, metadata.Username, path); + RemoteDatabaseStore.DeleteMetadata(path); + _recents?.Remove(path); + return true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + AppLog.Warn($"stale remote working copy could not be removed: {ex.Message}"); + return false; + } + } + + private static string Sha256Hex(byte[] bytes) + => Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(); +} diff --git a/apps/windows/Keepassity.Core/RemoteDatabaseStore.cs b/apps/windows/Keepassity.Core/RemoteDatabaseStore.cs index 7a7988b..3f8053a 100644 --- a/apps/windows/Keepassity.Core/RemoteDatabaseStore.cs +++ b/apps/windows/Keepassity.Core/RemoteDatabaseStore.cs @@ -1,16 +1,22 @@ // SPDX-License-Identifier: GPL-3.0-or-later using System.Security.Cryptography; using System.Text; +using System.Text.Json; -namespace Keepassity.Mock; +namespace Keepassity.Core; + +/// The remote source a working copy belongs to. +public sealed record RemoteSourceMetadata(string Url, string Username); /// /// Local working copies for databases opened from WebDAV. The KDBX bytes stay /// encrypted at rest; the folder only keeps a cached database per remote source. +/// A small metadata file records which remote source a working copy came from, +/// so stale cache entries can be identified safely later. /// public static class RemoteDatabaseStore { - public static string Root => Path.Combine(AppDataPaths.Root, "remote"); + public static string Root => Path.Combine(ApplicationPaths.Root, "remote"); /// Working-copy path for a remote file URL + username pair. public static string PathFor(string url, string username) @@ -21,4 +27,88 @@ public static string PathFor(string url, string username) Directory.CreateDirectory(Root); return Path.Combine(Root, name); } + + /// Metadata path for a working copy; null for paths outside the cache. + public static string? MetadataPathFor(string workingCopyPath) + { + try + { + string fullPath = Path.GetFullPath(workingCopyPath); + string root = Path.GetFullPath(Root); + if (!string.Equals(Path.GetDirectoryName(fullPath), root, + StringComparison.OrdinalIgnoreCase)) + { + return null; + } + return Path.Combine(root, + Path.GetFileNameWithoutExtension(fullPath) + ".source.json"); + } + catch + { + return null; + } + } + + /// + /// Record the remote source for a working copy. Best effort: the copy still + /// works without it, it just cannot be pruned as safely later. + /// + public static void WriteMetadata(string url, string username) + { + try + { + string? path = MetadataPathFor(PathFor(url, username)); + if (path is null) + { + return; + } + AtomicFile.Write(path, JsonSerializer.SerializeToUtf8Bytes( + new RemoteSourceMetadata(url.Trim(), username.Trim()))); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + AppLog.Warn($"remote working-copy metadata could not be written: {ex.Message}"); + } + } + + /// Read the remote source recorded for a working copy. + public static RemoteSourceMetadata? ReadMetadata(string workingCopyPath) + { + try + { + string? path = MetadataPathFor(workingCopyPath); + if (path is null || !File.Exists(path)) + { + return null; + } + RemoteSourceMetadata? metadata = JsonSerializer.Deserialize( + File.ReadAllText(path)); + return metadata is { Url.Length: > 0 } + ? metadata + : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException + or JsonException) + { + AppLog.Warn($"remote working-copy metadata is unreadable: {ex.Message}"); + return null; + } + } + + /// Remove the metadata file of a working copy (best effort). + public static void DeleteMetadata(string workingCopyPath) + { + try + { + string? path = MetadataPathFor(workingCopyPath); + if (path is not null && File.Exists(path)) + { + File.Delete(path); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + AppLog.Warn($"remote working-copy metadata could not be removed: {ex.Message}"); + } + } } diff --git a/apps/windows/Keepassity.Core/RemoteVaultOpener.cs b/apps/windows/Keepassity.Core/RemoteVaultOpener.cs new file mode 100644 index 0000000..041b792 --- /dev/null +++ b/apps/windows/Keepassity.Core/RemoteVaultOpener.cs @@ -0,0 +1,106 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Security.Cryptography; + +namespace Keepassity.Core; + +/// +/// A database downloaded from WebDAV that has not been written to its local +/// working copy yet. The bytes stay in memory until the master password opens +/// them, so a corrupted download, a wrong file or an HTML error page can never +/// become the local vault. +/// +public sealed class PendingRemoteDatabase +{ + public required string Url { get; init; } + public required string Username { get; init; } + public required string WorkingCopyPath { get; init; } + public required WebDavFileInfo Metadata { get; init; } + public required byte[] Bytes { get; init; } + + /// Backups kept when the verified bytes replace the working copy. + public int BackupRetention { get; init; } = 20; +} + +/// +/// Opens a database downloaded from WebDAV. The order is the data-safety rule: +/// open the bytes first (only the master password can do that), and only then +/// promote them to the working copy with the durable write protocol and record a +/// clean sync baseline. A failed open leaves both the working copy and its +/// baseline untouched. +/// +public sealed class RemoteVaultOpener +{ + private readonly SyncStateStore _states; + + public RemoteVaultOpener(SyncStateStore states) + { + _states = states ?? throw new ArgumentNullException(nameof(states)); + } + + /// Download the remote file and keep it pending. Never writes locally. + public async Task DownloadAsync(ISyncRemote remote, string url, + string username, int backupRetention = 20, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(remote); + WebDavFileInfo? metadata = await remote.GetMetadataAsync(cancellationToken); + if (metadata is null) + { + throw new WebDavException("the remote database file was not found", + statusCode: 404); + } + byte[] bytes = await remote.DownloadAsync(cancellationToken); + return new PendingRemoteDatabase + { + Url = url.Trim(), + Username = username.Trim(), + WorkingCopyPath = RemoteDatabaseStore.PathFor(url, username), + Metadata = metadata, + Bytes = bytes, + BackupRetention = backupRetention, + }; + } + + /// + /// Open with and, only + /// when it decrypts, replace the working copy and save the synced baseline. + /// Throws for a wrong password or a damaged file; + /// on any failure the core is locked again and nothing on disk changed. + /// + public async Task OpenAsync(PendingRemoteDatabase pending, ICoreClient core, + string password, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(pending); + ArgumentNullException.ThrowIfNull(core); + // The master password proves the download is a readable database before + // it is allowed to touch the working copy. + await core.OpenBytesAsync(pending.Bytes, password, pending.WorkingCopyPath) + .ConfigureAwait(false); + try + { + // Same durable protocol as a save: flushed sibling, backup of the + // previous working copy, atomic replace. Then the baseline, so a + // crash in between leaves the vault dirty instead of silently synced. + await Task.Run(() => AtomicFile.Replace(pending.WorkingCopyPath, pending.Bytes, + pending.BackupRetention, "download"), cancellationToken).ConfigureAwait(false); + SyncState state = _states.Load(pending.Url, pending.Username, + pending.WorkingCopyPath); + state.Etag = pending.Metadata.ETag; + state.Sha256 = Sha256Hex(pending.Bytes); + state.Size = pending.Bytes.Length; + state.RemoteModifiedUnix = pending.Metadata.ModifiedUnix; + state.LocalDirty = false; + state.LastSyncUnix = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + _states.Save(pending.Url, pending.Username, pending.WorkingCopyPath, state); + RemoteDatabaseStore.WriteMetadata(pending.Url, pending.Username); + } + catch + { + await core.LockAsync().ConfigureAwait(false); + throw; + } + } + + private static string Sha256Hex(byte[] bytes) + => Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(); +} diff --git a/apps/windows/Keepassity.Core/RunStateStore.cs b/apps/windows/Keepassity.Core/RunStateStore.cs new file mode 100644 index 0000000..5466531 --- /dev/null +++ b/apps/windows/Keepassity.Core/RunStateStore.cs @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Diagnostics; +using System.Text.Json; + +namespace Keepassity.Core; + +/// A run marker left behind by the previous process. +public sealed record PreviousRun(int ProcessId, DateTimeOffset StartedAt); + +/// +/// Detects an unclean shutdown: a marker is written when the window starts and +/// removed on a normal close. A marker whose process is gone means the previous +/// process died (crash, power loss, forced kill), so the next launch can point +/// the user at the backups even when the database itself opens fine. +/// +public sealed class RunStateStore +{ + private static readonly JsonSerializerOptions Options = new() + { + WriteIndented = true, + }; + + private sealed class RunState + { + public int Pid { get; set; } + public long StartedUnix { get; set; } + } + + private readonly string _path; + private readonly Func _isProcessRunning; + + /// Marker path; defaults to the application data root. + /// + /// Injectable process probe for headless tests; defaults to the real process table. + /// + public RunStateStore(string? path = null, Func? isProcessRunning = null) + { + _path = string.IsNullOrWhiteSpace(path) + ? System.IO.Path.Combine(ApplicationPaths.Root, "state", "run.json") + : System.IO.Path.GetFullPath(path); + _isProcessRunning = isProcessRunning ?? ProcessIsRunning; + } + + /// Absolute path of the marker file. + public string MarkerPath => _path; + + /// + /// The previous run that did not close cleanly, or null when the marker is + /// missing or belongs to a still-running instance (for example a second + /// window started with the test-only multiple-instance switch). A malformed + /// marker counts as an unclean run: the previous process did not get to write + /// a clean one. + /// + public PreviousRun? DetectPreviousCrash() + { + try + { + if (!File.Exists(_path)) + { + return null; + } + RunState? state = null; + try + { + state = JsonSerializer.Deserialize(File.ReadAllText(_path)); + } + catch (JsonException) + { + // Fall through: a damaged marker still means no clean close. + } + if (state is null || state.Pid <= 0) + { + return new PreviousRun(0, File.GetLastWriteTimeUtc(_path)); + } + if (_isProcessRunning(state.Pid)) + { + return null; + } + return new PreviousRun(state.Pid, + DateTimeOffset.FromUnixTimeSeconds(state.StartedUnix)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + AppLog.Warn($"run state could not be read: {ex.Message}"); + return null; + } + } + + /// Write the marker for this process. Best effort. + public void MarkRunning(DateTimeOffset? startedAt = null) + { + try + { + AtomicFile.Write(_path, JsonSerializer.SerializeToUtf8Bytes(new RunState + { + Pid = Environment.ProcessId, + StartedUnix = (startedAt ?? DateTimeOffset.UtcNow).ToUnixTimeSeconds(), + }, Options)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + AppLog.Warn($"run state could not be written: {ex.Message}"); + } + } + + /// Remove the marker on a clean close. Best effort. + public void Clear() + { + try + { + if (File.Exists(_path)) + { + File.Delete(_path); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + AppLog.Warn($"run state could not be cleared: {ex.Message}"); + } + } + + private static bool ProcessIsRunning(int processId) + { + try + { + using Process process = Process.GetProcessById(processId); + return !process.HasExited; + } + catch + { + return false; + } + } +} diff --git a/apps/windows/Keepassity.Core/SyncCoordinator.ConflictCopies.cs b/apps/windows/Keepassity.Core/SyncCoordinator.ConflictCopies.cs new file mode 100644 index 0000000..4e2ad92 --- /dev/null +++ b/apps/windows/Keepassity.Core/SyncCoordinator.ConflictCopies.cs @@ -0,0 +1,106 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Security.Cryptography; +using System.Text.Json; + +namespace Keepassity.Core; + +public sealed partial class SyncCoordinator +{ + + /// + /// Keep one local/remote copy pair for an unresolved conflict. The names are + /// derived from the two content hashes, so the same unresolved pair is reused + /// even after a restart instead of writing another timestamped pair into the + /// vault folder on every launch. + /// + private async Task<(string? LocalCopy, string? RemoteCopy)> PrepareConflictCopiesAsync( + SyncRun run, byte[] remote) + { + ConflictIdentity? identity = await ConflictIdentityAsync(run, remote); + if (identity is null) + { + return (null, null); + } + (string expectedLocal, string expectedRemote) = + ConflictCopyPaths(run.Document.Path, identity.Signature); + if (await FileHasHashAsync(expectedLocal, identity.LocalSha) && + await FileHasHashAsync(expectedRemote, identity.RemoteSha)) + { + _conflictLocalCopy = expectedLocal; + _conflictRemoteCopy = expectedRemote; + return (expectedLocal, expectedRemote); + } + _conflictLocalCopy = CreateConflictCopy(run.Document.Path, + "conflict", identity.ShortSignature, copySource: true, content: null); + _conflictRemoteCopy = CreateConflictCopy(run.Document.Path, + "remote conflict", identity.ShortSignature, copySource: false, content: remote); + return (_conflictLocalCopy, _conflictRemoteCopy); + } + + private async Task ConflictIdentityAsync(SyncRun run, byte[] remote) + { + try + { + byte[] local = await run.Document.ReadBytesAsync(); + string localSha = Sha256Hex(local); + string remoteSha = Sha256Hex(remote); + return new ConflictIdentity(localSha + ":" + remoteSha, localSha, remoteSha); + } + catch (IOException) + { + return null; + } + catch (UnauthorizedAccessException) + { + return null; + } + } + + private static Task FileHasHashAsync(string path, string expectedSha) + { + if (!File.Exists(path)) + { + return Task.FromResult(false); + } + try + { + string actual = Sha256Hex(File.ReadAllBytes(path)); + return Task.FromResult(string.Equals(actual, expectedSha, + StringComparison.OrdinalIgnoreCase)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return Task.FromResult(false); + } + } + + /// + /// Write a conflict copy under a deterministic name. An existing file with + /// the same name but different bytes (for example a user-edited conflict + /// copy) is never overwritten; the new copy gets a numeric suffix. + /// + private static string CreateConflictCopy(string databasePath, string label, + string shortSignature, bool copySource, byte[]? content) + { + string directory = Path.GetDirectoryName(databasePath)!; + string stem = Path.GetFileNameWithoutExtension(databasePath); + string extension = Path.GetExtension(databasePath); + string path = Path.Combine(directory, + $"{stem} ({label} {shortSignature}){extension}"); + int suffix = 1; + while (File.Exists(path)) + { + path = Path.Combine(directory, + $"{stem} ({label} {shortSignature}-{suffix++}){extension}"); + } + if (copySource) + { + AtomicFile.Copy(databasePath, path); + } + else + { + AtomicFile.Write(path, content!); + } + return path; + } +} diff --git a/apps/windows/Keepassity.Core/SyncCoordinator.Download.cs b/apps/windows/Keepassity.Core/SyncCoordinator.Download.cs new file mode 100644 index 0000000..f989748 --- /dev/null +++ b/apps/windows/Keepassity.Core/SyncCoordinator.Download.cs @@ -0,0 +1,195 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Security.Cryptography; +using System.Text.Json; + +namespace Keepassity.Core; + +public sealed partial class SyncCoordinator +{ + + private async Task DownloadAsync(SyncRun run, SyncState state, + WebDavFileInfo metadata) + { + byte[] bytes = await run.Remote.DownloadAsync(run.Cancellation); + if (await LocalChangedSinceStartAsync(run)) + { + return LocalChangedWhileSyncing(run, state); + } + string sha = Sha256Hex(bytes); + bool contentChanged = true; + if (!string.IsNullOrEmpty(state.Sha256)) + { + contentChanged = !string.Equals(sha, state.Sha256, StringComparison.OrdinalIgnoreCase); + } + else if (File.Exists(run.Document.Path)) + { + byte[] localBytes = await run.Document.ReadBytesAsync(); + contentChanged = !string.Equals(sha, Sha256Hex(localBytes), + StringComparison.OrdinalIgnoreCase); + } + if (contentChanged) + { + // The live database is only replaced after the downloaded bytes + // decrypt with the current master password. A redirect page or a + // corrupted body must not become the local vault; when the remote + // copy itself is unreadable the user decides whether to repair it. + SyncReport? unreadable = await VerifyRemoteOrRepairAsync(run, state, metadata, + bytes); + if (unreadable is not null) + { + return unreadable; + } + await run.Document.ReplaceAsync(bytes); + run.LocalShaAtStart = sha; + await run.Document.ReloadAsync(); + } + await run.Core.SyncCommitAsync(metadata.ETag, sha); + state.Etag = metadata.ETag; + state.Sha256 = sha; + state.Size = bytes.Length; + state.RemoteModifiedUnix = metadata.ModifiedUnix; + state.LocalDirty = false; + state.LastSyncUnix = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + SaveState(run, state); + ClearConflictCopies(); + Report(run.Status, "Synced"); + return new SyncReport(SyncOutcome.Synced, + contentChanged ? SyncNotice.Downloaded : SyncNotice.None); + } + + private async Task MergeAsync(SyncRun run, SyncState state, + WebDavFileInfo metadata) + { + byte[] remote = await run.Remote.DownloadAsync(run.Cancellation); + SyncReport? unreadable = await VerifyRemoteOrRepairAsync(run, state, metadata, + remote); + if (unreadable is not null) + { + return unreadable; + } + (string? localCopy, string? remoteCopy) = await PrepareConflictCopiesAsync(run, remote); + SyncMergeResult merged = await run.Document.MergeRemoteAsync(remote); + if (merged.Conflicts.Count == 0) + { + return await ApplyMergedAsync(run, state, metadata, merged, localCopy, remoteCopy); + } + + SyncConflictChoice choice = SyncConflictChoice.Cancel; + if (ConflictChoice is not null) + { + choice = await ConflictChoice( + new SyncConflictContext(localCopy, remoteCopy, merged.Conflicts)); + } + switch (choice) + { + case SyncConflictChoice.KeepLocal: + return await KeepLocalAsync(run, state, metadata, localCopy, remoteCopy); + case SyncConflictChoice.KeepRemote: + return await KeepRemoteAsync(run, state, metadata, remote, localCopy, + remoteCopy); + case SyncConflictChoice.KeepBoth: + return await ApplyMergedAsync(run, state, metadata, merged, localCopy, + remoteCopy); + default: + state.LocalDirty = true; + SaveState(run, state); + Report(run.Status, "Conflict"); + return new SyncReport(SyncOutcome.ConflictPaused, SyncNotice.ConflictPaused, + localCopy, remoteCopy); + } + } + + private async Task ApplyMergedAsync(SyncRun run, SyncState state, + WebDavFileInfo metadata, SyncMergeResult merged, string? localCopy, + string? remoteCopy) + { + if (await LocalChangedSinceStartAsync(run)) + { + return LocalChangedWhileSyncing(run, state); + } + bool autoMerged = merged.Conflicts.Count == 0; + await run.Document.ReplaceAsync(merged.Bytes); + run.LocalShaAtStart = Sha256Hex(merged.Bytes); + await run.Document.ReloadAsync(); + string? etag; + try + { + etag = await run.Remote.UploadAsync(merged.Bytes, metadata.ETag, run.Cancellation); + } + catch (WebDavException ex) when (ex.Conflict) + { + state.LocalDirty = true; + SaveState(run, state); + Report(run.Status, "Conflict"); + return new SyncReport(SyncOutcome.RemoteChanged, + SyncNotice.MergedRemoteChanged, localCopy, remoteCopy); + } + await CommitSyncedAsync(run, state, merged.Bytes, etag, metadata, + autoMerged ? "Synced" : "Merged"); + return new SyncReport(SyncOutcome.Merged, + autoMerged ? SyncNotice.MergedAutomatically : SyncNotice.MergedKeptBoth, + localCopy, remoteCopy); + } + + private async Task KeepLocalAsync(SyncRun run, SyncState state, + WebDavFileInfo metadata, string? localCopy, string? remoteCopy) + { + byte[] localBytes = await run.Document.ReadBytesAsync(); + string? etag; + try + { + etag = await run.Remote.UploadAsync(localBytes, metadata.ETag, run.Cancellation); + } + catch (WebDavException ex) when (ex.Conflict) + { + state.LocalDirty = true; + SaveState(run, state); + Report(run.Status, "Conflict"); + return new SyncReport(SyncOutcome.RemoteChanged, + SyncNotice.KeptLocalRemoteChanged, localCopy, remoteCopy); + } + await CommitSyncedAsync(run, state, localBytes, etag, metadata, "Synced"); + return new SyncReport(SyncOutcome.Synced, SyncNotice.KeptLocal, localCopy, remoteCopy); + } + + private async Task KeepRemoteAsync(SyncRun run, SyncState state, + WebDavFileInfo metadata, byte[] remote, string? localCopy, string? remoteCopy) + { + if (await LocalChangedSinceStartAsync(run)) + { + return LocalChangedWhileSyncing(run, state); + } + // MergeAsync verified these exact bytes before asking the conflict question. + await run.Document.ReplaceAsync(remote); + run.LocalShaAtStart = Sha256Hex(remote); + await run.Document.ReloadAsync(); + await CommitSyncedAsync(run, state, remote, metadata.ETag, metadata, "Synced"); + return new SyncReport(SyncOutcome.Synced, SyncNotice.KeptRemote, localCopy, + remoteCopy); + } + + /// + /// Record a successful sync: commit the baseline in the core, persist the + /// sidecar, drop the conflict copies bookkeeping and report the status. + /// The order matters: the core validates the hash before the sidecar claims + /// the vault is clean, so a crash between the two leaves it dirty. + /// + private async Task CommitSyncedAsync(SyncRun run, SyncState state, byte[] bytes, + string? etag, WebDavFileInfo? metadata, string statusSource) + { + string sha = Sha256Hex(bytes); + await run.Core.SyncCommitAsync(etag, sha); + state.Etag = etag; + state.Sha256 = sha; + state.Size = bytes.Length; + if (metadata is not null) + { + state.RemoteModifiedUnix = metadata.ModifiedUnix; + } + state.LocalDirty = false; + state.LastSyncUnix = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + SaveState(run, state); + ClearConflictCopies(); + Report(run.Status, statusSource); + } +} diff --git a/apps/windows/Keepassity.Core/SyncCoordinator.Repair.cs b/apps/windows/Keepassity.Core/SyncCoordinator.Repair.cs new file mode 100644 index 0000000..2204866 --- /dev/null +++ b/apps/windows/Keepassity.Core/SyncCoordinator.Repair.cs @@ -0,0 +1,146 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Security.Cryptography; +using System.Text.Json; + +namespace Keepassity.Core; + +public sealed partial class SyncCoordinator +{ + + /// + /// True when the local file no longer has the bytes this run started with: + /// a save landed after the decision, so applying the older sync result would + /// silently undo it. + /// + private static async Task LocalChangedSinceStartAsync(SyncRun run) + { + if (run.LocalShaAtStart is null || !File.Exists(run.Document.Path)) + { + return false; + } + byte[] current = await run.Document.ReadBytesAsync(); + return !string.Equals(Sha256Hex(current), run.LocalShaAtStart, + StringComparison.OrdinalIgnoreCase); + } + + /// + /// Stop before replacing or uploading: keep the newer local save, mark the + /// vault dirty and let the next sync merge the two sides. + /// + private SyncReport LocalChangedWhileSyncing(SyncRun run, SyncState state) + { + AppLog.Info("sync: the local database changed during the run; pausing"); + state.LocalDirty = true; + SaveState(run, state); + Report(run.Status, "Local changed"); + return new SyncReport(SyncOutcome.ConflictPaused, + SyncNotice.LocalChangedWhileSyncing); + } + + /// + /// Verify downloaded remote bytes before they may replace anything. Returns a + /// report when the remote copy cannot be opened; the caller then returns it + /// unchanged. A null result means the bytes are readable. + /// + private async Task VerifyRemoteOrRepairAsync(SyncRun run, SyncState state, + WebDavFileInfo metadata, byte[] remote) + { + RequireMasterPassword(run); + try + { + await run.Core.VerifyAsync(remote, run.MasterPassword!); + return null; + } + catch (CoreException ex) when (IsUnreadableRemote(ex)) + { + return await RepairUnreadableRemoteAsync(run, state, metadata, remote, ex); + } + } + + /// + /// An unreadable remote copy never overwrites the local vault. Its exact bytes + /// are first preserved next to the local database (the server copy may be the + /// only other copy of data, or may be a valid database protected by a different + /// password). By default the run then pauses; only an explicit user choice + /// () uploads the verified local copy. + /// + private async Task RepairUnreadableRemoteAsync(SyncRun run, SyncState state, + WebDavFileInfo metadata, byte[] remote, CoreException cause) + { + string? preserved = await PreserveUnreadableRemoteAsync(run, remote); + if (!OverwriteUnreadableRemote) + { + state.LocalDirty = true; + SaveState(run, state); + AppLog.Warn("sync: the remote database cannot be opened with this password; " + + "keeping the local copy"); + Report(run.Status, "Remote unreadable"); + return new SyncReport(SyncOutcome.RemoteUnreadable, + SyncNotice.RemoteUnreadable, RemoteCopy: preserved, Reason: cause.Code); + } + AppLog.Warn("sync: replacing an unreadable remote database with the verified local copy"); + byte[] localBytes = await run.Document.ReadBytesAsync(); + string? etag; + try + { + etag = await run.Remote.UploadAsync(localBytes, metadata.ETag, + run.Cancellation); + } + catch (WebDavException ex) when (ex.Conflict) + { + state.LocalDirty = true; + SaveState(run, state); + Report(run.Status, "Conflict"); + return new SyncReport(SyncOutcome.RemoteChanged, + SyncNotice.RemoteUnreadableRemoteChanged, RemoteCopy: preserved); + } + await CommitSyncedAsync(run, state, localBytes, etag, metadata, "Remote repaired"); + return new SyncReport(SyncOutcome.Synced, SyncNotice.RemoteRepaired, + RemoteCopy: preserved); + } + + /// + /// Keep the unreadable remote bytes under a deterministic hash-derived name next + /// to the local database before any repair can overwrite them. Best effort: a + /// failure to preserve must not block the safe default of keeping local data. + /// + private static async Task PreserveUnreadableRemoteAsync(SyncRun run, + byte[] remote) + { + try + { + string databasePath = run.Document.Path; + string directory = Path.GetDirectoryName(databasePath)!; + string stem = Path.GetFileNameWithoutExtension(databasePath); + string extension = Path.GetExtension(databasePath); + string hash = Sha256Hex(remote); + string path = Path.Combine(directory, + $"{stem} (unreadable remote {hash[..8]}){extension}"); + int suffix = 1; + while (File.Exists(path)) + { + try + { + if (string.Equals(Sha256Hex(File.ReadAllBytes(path)), hash, + StringComparison.OrdinalIgnoreCase)) + { + return path; + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Unreadable existing file: choose another name below. + } + path = Path.Combine(directory, + $"{stem} (unreadable remote {hash[..8]}-{suffix++}){extension}"); + } + await Task.Run(() => AtomicFile.Write(path, remote)); + return path; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + AppLog.Warn($"the unreadable remote copy could not be preserved: {ex.Message}"); + return null; + } + } +} diff --git a/apps/windows/Keepassity.Core/SyncCoordinator.Upload.cs b/apps/windows/Keepassity.Core/SyncCoordinator.Upload.cs new file mode 100644 index 0000000..6f42d46 --- /dev/null +++ b/apps/windows/Keepassity.Core/SyncCoordinator.Upload.cs @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Security.Cryptography; +using System.Text.Json; + +namespace Keepassity.Core; + +public sealed partial class SyncCoordinator +{ + + private async Task UpToDateAsync(SyncRun run, SyncState state, + WebDavFileInfo metadata, bool degraded) + { + if (string.IsNullOrEmpty(state.Sha256)) + { + // The remote says unchanged, but there is no content hash to record + // as a baseline. Do not mark the vault clean; a later sync could + // otherwise overwrite local edits. + state.LocalDirty = true; + SaveState(run, state); + Report(run.Status, "Sync needs baseline"); + return new SyncReport(SyncOutcome.NeedsBaseline); + } + state.Etag = metadata.ETag; + state.Size = metadata.Size; + state.RemoteModifiedUnix = metadata.ModifiedUnix; + state.LocalDirty = false; + state.LastSyncUnix = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + await run.Core.SyncCommitAsync(state.Etag, state.Sha256); + SaveState(run, state); + Report(run.Status, degraded ? "Synced (degraded)" : "Synced"); + return new SyncReport(SyncOutcome.Synced, Degraded: degraded); + } + + /// + /// Upload with the same 0.5 s / 1.5 s / 4 s back-off schedule as the core + /// sync state machine. A 412 (remote changed during the upload) is retried + /// three times; after the last retry the remote change is resolved through the + /// normal merge/conflict path, so the remote is never overwritten silently. + /// + private async Task UploadWithBackoffAsync(SyncRun run, SyncState state) + { + for (int attempt = 0; ; attempt++) + { + try + { + return await UploadAsync(run, state); + } + catch (WebDavException ex) when (ex.Conflict) + { + if (attempt >= UploadConflictRetries) + { + AppLog.Warn("sync: PUT 412 after three back-off retries; merging"); + WebDavFileInfo? metadata = + await run.Remote.GetMetadataAsync(run.Cancellation); + if (metadata is null) + { + throw; + } + Report(run.Status, "Resolving conflict"); + return await MergeAsync(run, state, metadata); + } + int delayMs = attempt switch + { + 0 => 500, + 1 => 1500, + _ => 4000, + }; + Report(run.Status, "Retrying sync in {0} ms", delayMs); + AppLog.Warn($"sync: PUT 412, retry {attempt + 1}/3 after {delayMs} ms"); + await _delayAsync(TimeSpan.FromMilliseconds(delayMs), run.Cancellation); + } + } + } + + private async Task UploadAsync(SyncRun run, SyncState state) + { + byte[] bytes = await run.Core.SaveBytesAsync(); + string bytesSha = Sha256Hex(bytes); + // The snapshot above can be older than a save that landed while the core + // was serializing it; writing the snapshot would then undo that save. + if (run.LocalShaAtStart is not null && File.Exists(run.Document.Path)) + { + byte[] current = await run.Document.ReadBytesAsync(); + string currentSha = Sha256Hex(current); + if (!string.Equals(currentSha, run.LocalShaAtStart, + StringComparison.OrdinalIgnoreCase) && + !string.Equals(currentSha, bytesSha, StringComparison.OrdinalIgnoreCase)) + { + return LocalChangedWhileSyncing(run, state); + } + } + await run.Document.ReplaceAsync(bytes); + // The coordinator itself just wrote the file; remember it so the + // during-run edit guard only reacts to changes made after this point. + run.LocalShaAtStart = bytesSha; + string? etag = await run.Remote.UploadAsync(bytes, state.Etag, run.Cancellation); + string sha = Sha256Hex(bytes); + await run.Core.SyncCommitAsync(etag, sha); + state.Etag = etag; + state.Sha256 = sha; + state.Size = bytes.Length; + state.LocalDirty = false; + state.LastSyncUnix = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + SaveState(run, state); + ClearConflictCopies(); + Report(run.Status, "Synced"); + return new SyncReport(SyncOutcome.Synced); + } +} diff --git a/apps/windows/Keepassity.Core/SyncCoordinator.cs b/apps/windows/Keepassity.Core/SyncCoordinator.cs new file mode 100644 index 0000000..a97376c --- /dev/null +++ b/apps/windows/Keepassity.Core/SyncCoordinator.cs @@ -0,0 +1,307 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Security.Cryptography; +using System.Text.Json; + +namespace Keepassity.Core; + + +/// Inputs for one sync run. +public sealed class SyncOptions +{ + public required string RemoteUrl { get; init; } + public required string Username { get; init; } + + /// + /// The current master password. Required before downloaded or remote-chosen + /// bytes replace the local database; null/empty means the vault is locked and + /// the run fails closed instead of writing unverified bytes. + /// + public string? MasterPassword { get; init; } +} + +/// How a sync run ended, independent of how the shell renders it. +public enum SyncOutcome +{ + /// Local and remote are in sync (uploaded, downloaded or already equal). + Synced, + + /// A merge was applied and uploaded. + Merged, + + /// The remote is unchanged but no content hash exists to prove it. + NeedsBaseline, + + /// The core asked to retry later; nothing was written. + Retry, + + /// The remote is unreachable; nothing was written. + Offline, + + /// The user paused the conflict; both copies are untouched and dirty. + ConflictPaused, + + /// The local merged/kept bytes were applied but the remote changed again. + RemoteChanged, + + /// + /// The remote copy cannot be opened with the master password; nothing local + /// was touched and the user has to decide whether to replace it. + /// + RemoteUnreadable, +} + +/// The user-visible follow-up the shell should show after a run. +public enum SyncNotice +{ + None, + Downloaded, + MergedAutomatically, + MergedKeptBoth, + KeptLocal, + KeptRemote, + ConflictPaused, + MergedRemoteChanged, + KeptLocalRemoteChanged, + LocalChangedWhileSyncing, + RemoteUnreadable, + RemoteRepaired, + RemoteUnreadableRemoteChanged, +} + +/// Result of a sync run: what happened and which notice to surface. +public sealed record SyncReport( + SyncOutcome Outcome, + SyncNotice Notice = SyncNotice.None, + string? LocalCopy = null, + string? RemoteCopy = null, + string? Reason = null, + bool Degraded = false); + +/// +/// One status line for the navigation pane. The source string is an untranslated +/// catalog key; the shell renders it through the localization facade. +/// +public sealed record SyncStatusUpdate(string Source, object?[] Arguments); + +/// What the shell needs to ask the user how to resolve a conflict. +public sealed record SyncConflictContext( + string? LocalCopy, + string? RemoteCopy, + IReadOnlyList Conflicts); + +/// The user's answer to a three-way merge conflict. +public enum SyncConflictChoice +{ + Cancel, + KeepLocal, + KeepRemote, + KeepBoth, +} + +/// +/// Runs one WebDAV sync: decide, upload with back-off, download, three-way merge +/// and the conflict rules, then record the new baseline. +/// +/// This is the application-service layer of the sync protocol. Keeping it out of +/// the window is what makes the ordering rules testable: the local database is +/// only replaced by bytes that were verified with the master password, the disk +/// write always happens before the in-memory baseline commit, the baseline is +/// only saved after the core accepted it, and a failed step leaves the vault +/// dirty rather than silently clean. +/// +public sealed partial class SyncCoordinator +{ + private const int UploadConflictRetries = 3; + + private readonly SyncStateStore _states; + private readonly Func _delayAsync; + + // One local/remote copy pair per unresolved conflict: a repeated attempt for + // the same pair reuses the copies instead of writing another pair each time. + private string? _conflictLocalCopy; + private string? _conflictRemoteCopy; + + /// + /// Wait used by the upload back-off. Tests pass an immediate waiter so the + /// retry schedule can be asserted without real waiting; the shell uses + /// . + /// + public SyncCoordinator(SyncStateStore states, + Func? delayAsync = null) + { + _states = states ?? throw new ArgumentNullException(nameof(states)); + _delayAsync = delayAsync ?? Task.Delay; + } + + /// + /// Asked only when the three-way merge left conflicts. When unset (headless + /// runs and tests) the run pauses the conflict without writing anything. + /// + public Func>? ConflictChoice { get; set; } + + /// + /// One-shot explicit user choice: when the downloaded remote copy cannot be + /// opened with the master password, replace it with the verified local copy + /// instead of pausing. Never enabled without asking the user: the unreadable + /// remote may still be the only copy of data the user can recover elsewhere. + /// + public bool OverwriteUnreadableRemote { get; set; } + + /// + /// Execute one sync run against . Network and core + /// exceptions propagate to the caller unchanged; anything already written to + /// disk has a recorded dirty baseline at that point. + /// + public async Task RunAsync(ISyncRemote remote, IVaultDocument document, + ICoreClient core, SyncOptions options, Action? status = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(remote); + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(core); + ArgumentNullException.ThrowIfNull(options); + var run = new SyncRun( + remote, + document, + core, + options.RemoteUrl.Trim(), + options.Username.Trim(), + options.MasterPassword, + status, + cancellationToken); + return await ExecuteAsync(run); + } + + private sealed record SyncRun( + ISyncRemote Remote, + IVaultDocument Document, + ICoreClient Core, + string Url, + string Username, + string? MasterPassword, + Action? Status, + CancellationToken Cancellation) + { + /// + /// Hash of the local file when this run started. A save that lands while + /// the run downloads, merges or verifies must not be overwritten by the + /// older result the decision was based on. + /// + public string? LocalShaAtStart { get; set; } + } + + private async Task ExecuteAsync(SyncRun run) + { + SyncState state = _states.Load(run.Url, run.Username, run.Document.Path); + byte[]? localAtStart = File.Exists(run.Document.Path) + ? await run.Document.ReadBytesAsync() + : null; + if (localAtStart is not null) + { + run.LocalShaAtStart = Sha256Hex(localAtStart); + } + if (!string.IsNullOrEmpty(state.Sha256)) + { + await run.Core.SyncCommitAsync(state.Etag, state.Sha256); + // The sidecar is only clean if the local file still is the bytes that + // were synced. A crash between the database write and the sidecar + // write leaves the old sidecar behind; treat the vault as dirty + // instead of letting the next sync no-op and lose the upload. + if (localAtStart is not null && + !string.Equals(run.LocalShaAtStart, state.Sha256, + StringComparison.OrdinalIgnoreCase)) + { + AppLog.Warn( + "sync: local database differs from the synced baseline; treating it as dirty"); + state.LocalDirty = true; + } + } + + WebDavFileInfo? metadata = await run.Remote.GetMetadataAsync(run.Cancellation); + if (metadata is null) + { + // The remote file does not exist yet: the local database becomes the + // first version on the server. + return await UploadWithBackoffAsync(run, state); + } + + string remoteMeta = JsonSerializer.Serialize(new + { + etag = metadata.ETag, + size = metadata.Size, + modified_unix = metadata.ModifiedUnix, + reliability = metadata.ETag is null ? "degraded" : "full", + }); + SyncDecisionDto decision = await run.Core.SyncDecideAsync(remoteMeta, state.LocalDirty); + switch (decision.Action) + { + case "up_to_date": + return await UpToDateAsync(run, state, metadata, decision.Degraded); + case "upload": + return await UploadWithBackoffAsync(run, state); + case "download": + return await DownloadAsync(run, state, metadata); + case "download_and_merge": + case "conflict": + return await MergeAsync(run, state, metadata); + case "retry": + Report(run.Status, "Sync retry"); + return new SyncReport(SyncOutcome.Retry); + case "offline": + default: + Report(run.Status, "Offline"); + return new SyncReport(SyncOutcome.Offline, Reason: decision.Reason); + } + } + + private sealed record ConflictIdentity(string Signature, string LocalSha, + string RemoteSha) + { + /// Compact name-safe form used in the copy file names. + public string ShortSignature => LocalSha[..8] + "-" + RemoteSha[..8]; + } + + private static (string Local, string Remote) ConflictCopyPaths(string databasePath, + string signature) + { + string directory = Path.GetDirectoryName(databasePath)!; + string stem = Path.GetFileNameWithoutExtension(databasePath); + string extension = Path.GetExtension(databasePath); + string[] parts = signature.Split(':'); + string shortSignature = parts.Length == 2 && parts[0].Length >= 8 && + parts[1].Length >= 8 + ? parts[0][..8] + "-" + parts[1][..8] + : signature.Replace(':', '-')[..Math.Min(16, signature.Length)]; + return ( + Path.Combine(directory, $"{stem} (conflict {shortSignature}){extension}"), + Path.Combine(directory, $"{stem} (remote conflict {shortSignature}){extension}")); + } + + private static bool IsUnreadableRemote(CoreException ex) + => ex.Code is "BadPassword" or "CorruptDatabase" or "Corrupt"; + + private static void RequireMasterPassword(SyncRun run) + { + if (string.IsNullOrEmpty(run.MasterPassword)) + { + throw new InvalidOperationException( + "Unlock the vault before applying remote changes."); + } + } + + private void SaveState(SyncRun run, SyncState state) + => _states.Save(run.Url, run.Username, run.Document.Path, state); + + private void ClearConflictCopies() + { + _conflictLocalCopy = null; + _conflictRemoteCopy = null; + } + + private static void Report(Action? status, string source, + params object?[] arguments) + => status?.Invoke(new SyncStatusUpdate(source, arguments)); + + private static string Sha256Hex(byte[] bytes) + => Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(); +} diff --git a/apps/windows/Keepassity.Core/SyncStateStore.cs b/apps/windows/Keepassity.Core/SyncStateStore.cs index 1b9c64e..87bc3f5 100644 --- a/apps/windows/Keepassity.Core/SyncStateStore.cs +++ b/apps/windows/Keepassity.Core/SyncStateStore.cs @@ -3,7 +3,7 @@ using System.Text; using System.Text.Json; -namespace Keepassity.Mock; +namespace Keepassity.Core; public sealed class SyncState { @@ -25,9 +25,15 @@ public sealed class SyncStateStore private readonly string _directory; - public SyncStateStore() + /// + /// is for tests and diagnostics; the app uses + /// the application data root. + /// + public SyncStateStore(string? directory = null) { - _directory = Path.Combine(AppDataPaths.Root, "state"); + _directory = string.IsNullOrWhiteSpace(directory) + ? Path.Combine(ApplicationPaths.Root, "state") + : Path.GetFullPath(directory); try { Directory.CreateDirectory(_directory); @@ -47,40 +53,99 @@ public SyncState Load(string remoteUrl, string username, string localPath) public void Save(string remoteUrl, string username, string localPath, SyncState state) => SaveTo(PathFor(remoteUrl, username, localPath), state); + /// Sidecar path for one remote source/local path pair. + public string StatePathFor(string remoteUrl, string username, string localPath) + => PathFor(remoteUrl, username, localPath); + + /// Remove the sidecar (used when a cached working copy is deleted). + public void Remove(string remoteUrl, string username, string localPath) + { + try + { + string path = PathFor(remoteUrl, username, localPath); + if (File.Exists(path)) + { + File.Delete(path); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + AppLog.Warn($"sync state could not be removed: {ex.Message}"); + } + } + private SyncState LoadFrom(string path) { if (!Available) { - return new SyncState(); + // Without a state directory the baseline is unknown. Do not report + // "clean": a clean baseline is what lets a sync overwrite local data. + return new SyncState { LocalDirty = true }; } - try + SyncState? state = null; + bool existed = File.Exists(path); + if (existed) { - if (File.Exists(path)) + try + { + state = JsonSerializer.Deserialize(File.ReadAllText(path), Options); + } + catch (Exception ex) { - SyncState? state = JsonSerializer.Deserialize( - File.ReadAllText(path), Options); - if (state is not null) - { - return state; - } + PreserveCorruptFile(path); + AppLog.Warn($"sync state is unreadable; treating the vault as dirty: {ex.Message}"); } } - catch + if (state is null) { - // Corrupt sidecar: start with a clean baseline. + if (existed) + { + PreserveCorruptFile(path); + } + // Missing on first sync is normal and clean. An existing but + // unreadable sidecar is not: fail closed so the next sync uploads + // or merges instead of overwriting the local database. + return new SyncState { LocalDirty = existed }; + } + if (!IsSha256(state.Sha256)) + { + // A half-written baseline from an older build cannot prove the + // local and remote copies match; keep the local edits. + state.LocalDirty = true; } - return new SyncState(); + return state; } + private static bool IsSha256(string? value) + => value is { Length: 64 } && + value.All(character => character is >= '0' and <= '9' or >= 'a' and <= 'f' + or >= 'A' and <= 'F'); + private void SaveTo(string path, SyncState state) { if (!Available) { return; } - string temp = path + ".tmp"; - File.WriteAllText(temp, JsonSerializer.Serialize(state, Options)); - File.Move(temp, path, true); + AtomicFile.Write(path, JsonSerializer.SerializeToUtf8Bytes(state, Options)); + } + + private static void PreserveCorruptFile(string path) + { + try + { + if (!File.Exists(path)) + { + return; + } + string backup = path + ".corrupt-" + DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + File.Copy(path, backup, overwrite: false); + AppLog.Warn($"preserved unreadable sync state as {Path.GetFileName(backup)}"); + } + catch + { + // Diagnostics must not prevent a sync from proceeding dirty. + } } private string PathFor(string remoteUrl, string username, string localPath) diff --git a/apps/windows/Keepassity.Core/TrayMenuPlacement.cs b/apps/windows/Keepassity.Core/TrayMenuPlacement.cs index 611342c..4c1a5c4 100644 --- a/apps/windows/Keepassity.Core/TrayMenuPlacement.cs +++ b/apps/windows/Keepassity.Core/TrayMenuPlacement.cs @@ -1,5 +1,5 @@ // SPDX-License-Identifier: GPL-3.0-or-later -namespace Keepassity.Mock; +namespace Keepassity.Core; /// /// Pure placement decisions for the tray menu flyout. Kept out of the WinUI diff --git a/apps/windows/Keepassity.Core/VaultFileLock.cs b/apps/windows/Keepassity.Core/VaultFileLock.cs new file mode 100644 index 0000000..2be7d7f --- /dev/null +++ b/apps/windows/Keepassity.Core/VaultFileLock.cs @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Security.Cryptography; +using System.Text; + +namespace Keepassity.Core; + +/// +/// Advisory lock for one database path. Two layers protect the file: an +/// account-scoped lock under the application data folder and, when the vault +/// folder is writable, an exclusive lock inside the vault's own +/// .keepassity/locks folder. The second layer is what coordinates a +/// database on a network share between different Windows accounts or machines, +/// where the per-account lock cannot see the other side. The operating system +/// releases both file handles when the process dies, so a crash leaves no +/// permanent lock. +/// +public sealed class VaultFileLock : IDisposable +{ + private readonly string _path; + private readonly string? _sharedPath; + private FileStream? _stream; + private FileStream? _sharedStream; + + private VaultFileLock(string path, FileStream stream, string? sharedPath = null, + FileStream? sharedStream = null) + { + _path = path; + _stream = stream; + _sharedPath = sharedPath; + _sharedStream = sharedStream; + } + + /// Absolute database path this lock belongs to. + public string DatabasePath { get; private set; } = string.Empty; + + /// + /// Shared lock file next to the database, or null when the vault folder + /// could not hold one (read-only folder or a not-yet-created database + /// directory). Diagnostics/tests use it to observe whether cross-machine + /// coordination is active. + /// + public string? SharedLockPath => _sharedPath; + + /// + /// Path of the lock file shared between accounts/machines for a database. + /// It lives in the database's own .keepassity folder so every client + /// opening the same shared folder sees the same lock file. + /// + public static string SharedLockPathFor(string databasePath) + { + string fullPath = Path.GetFullPath(databasePath); + string directory = Path.GetDirectoryName(fullPath)!; + return Path.Combine(directory, ".keepassity", "locks", + Path.GetFileName(fullPath) + ".lock"); + } + + /// + /// Try to take the exclusive lock. Returns null when another process, + /// account or machine owns it (or the account lock file cannot be created); + /// carries a diagnostic for the log, not + /// necessarily user-facing text. + /// + public static VaultFileLock? TryAcquire(string databasePath, out string? error) + { + error = null; + string fullPath; + string localPath; + FileStream local; + try + { + fullPath = Path.GetFullPath(databasePath); + localPath = LocalLockPath(fullPath); + local = OpenExclusive(localPath); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + error = ex.Message; + return null; + } + + string? sharedPath = null; + FileStream? shared = null; + try + { + string directory = Path.GetDirectoryName(fullPath)!; + if (!Directory.Exists(directory)) + { + // The database is being created: the create-only write protects + // the first bytes, and the next open takes the shared lock. + return new VaultFileLock(localPath, local) { DatabasePath = fullPath }; + } + sharedPath = SharedLockPathFor(fullPath); + Directory.CreateDirectory(Path.GetDirectoryName(sharedPath)!); + shared = OpenExclusive(sharedPath); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + bool contended = ex is IOException && sharedPath is not null && + File.Exists(sharedPath); + if (contended) + { + local.Dispose(); + error = "the database is open in another Keepassity instance " + + "(shared-folder lock)"; + return null; + } + // A read-only or otherwise unwritable vault folder keeps the old + // account-only protection instead of refusing to open the database. + AppLog.Info($"shared-folder lock unavailable ({ex.Message}); " + + "only this Windows account is protected"); + if (shared is not null) + { + shared.Dispose(); + shared = null; + } + sharedPath = null; + } + return new VaultFileLock(localPath, local, sharedPath, shared) + { + DatabasePath = fullPath, + }; + } + + public void Dispose() + { + DisposeStream(ref _stream); + DisposeStream(ref _sharedStream); + try + { + File.Delete(_path); + } + catch + { + // A stale zero-byte lock file is harmless: FileShare.None on a fresh + // open is what enforces the lock, not the file's existence. + } + if (_sharedPath is null) + { + return; + } + try + { + File.Delete(_sharedPath); + } + catch + { + // Same reasoning as the account lock above. + } + try + { + string lockDirectory = Path.GetDirectoryName(_sharedPath)!; + if (Directory.Exists(lockDirectory) && + Directory.GetFileSystemEntries(lockDirectory).Length == 0) + { + Directory.Delete(lockDirectory); + } + } + catch + { + // An empty ".keepassity/locks" folder is harmless and may be used by + // another open database in the same folder. + } + } + + private static string LocalLockPath(string fullPath) + { + string directory = Path.Combine(ApplicationPaths.Root, "locks"); + Directory.CreateDirectory(directory); + string key = Convert.ToHexString(SHA256.HashData( + Encoding.UTF8.GetBytes(fullPath.ToLowerInvariant()))).ToLowerInvariant(); + return Path.Combine(directory, key + ".lock"); + } + + private static FileStream OpenExclusive(string path) + => new(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, 4096, + FileOptions.WriteThrough); + + private static void DisposeStream(ref FileStream? stream) + { + FileStream? current = stream; + stream = null; + if (current is null) + { + return; + } + try + { + current.Dispose(); + } + catch + { + // The handle is released by the OS even if Dispose reports a cached + // write error; the lock itself is gone either way. + } + } +} diff --git a/apps/windows/Keepassity.Core/VaultFingerprint.cs b/apps/windows/Keepassity.Core/VaultFingerprint.cs new file mode 100644 index 0000000..e9da2aa --- /dev/null +++ b/apps/windows/Keepassity.Core/VaultFingerprint.cs @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Security.Cryptography; + +namespace Keepassity.Core; + +/// +/// Content identity of a database file at a point in time. Before a save the +/// shell compares this with the file on disk; if another program (or user) +/// changed it, the save is refused instead of silently overwriting their work. +/// SHA-256 is authoritative; length and mtime are diagnostics only. +/// +public readonly record struct VaultFingerprint(long Length, DateTime LastWriteTimeUtc, + string Sha256) +{ + public static VaultFingerprint Capture(string path) + { + byte[] bytes = File.ReadAllBytes(path); + return new VaultFingerprint( + bytes.LongLength, + File.GetLastWriteTimeUtc(path), + Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant()); + } + + /// True when both snapshots describe the same bytes. + public bool Matches(VaultFingerprint other) => + string.Equals(Sha256, other.Sha256, StringComparison.Ordinal); +} diff --git a/apps/windows/Keepassity.Core/VaultProfileStore.cs b/apps/windows/Keepassity.Core/VaultProfileStore.cs new file mode 100644 index 0000000..ca19ce4 --- /dev/null +++ b/apps/windows/Keepassity.Core/VaultProfileStore.cs @@ -0,0 +1,218 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Keepassity.Core; + +/// +/// Settings that belong to one database rather than to the application: +/// where its WebDAV source is, and the switches that only make sense for it. +/// +/// The WebDAV password is deliberately absent: it lives in the DPAPI store, +/// keyed by URL and user name, so it is machine-bound and never travels with a +/// copied settings file. +/// +public sealed class VaultProfile +{ + /// Root-group UUID of the database (the format has no database UUID). + [JsonPropertyName("uuid")] public string Uuid { get; set; } = ""; + + /// Display name last reported by the file. + [JsonPropertyName("name")] public string? Name { get; set; } + + [JsonPropertyName("webdav_url")] public string? WebDavUrl { get; set; } + [JsonPropertyName("webdav_username")] public string? WebDavUsername { get; set; } + + /// Upload after every save. + [JsonPropertyName("sync_on_save")] public bool SyncOnSave { get; set; } = true; + + /// How many pre-save backups this database keeps. + [JsonPropertyName("backup_retention")] public int BackupRetention { get; set; } = 20; + + /// Last successful sync, Unix seconds (display only). + [JsonPropertyName("last_sync_unix")] public long? LastSyncUnix { get; set; } +} + +/// +/// The per-vault settings file (vaults.json), keyed by database UUID. +/// +/// One file per user, one entry per database, one WebDAV source per entry: the +/// source is a property of the database, not a global switch, which is what kept +/// the second vault from silently syncing to the first one's server. +/// +public sealed class VaultProfileStore +{ + private const int CurrentSchema = 1; + + private static readonly JsonSerializerOptions Options = new() + { + WriteIndented = true, + }; + + private sealed class FileModel + { + [JsonPropertyName("schema_version")] public int SchemaVersion { get; set; } = CurrentSchema; + [JsonPropertyName("profiles")] public List Profiles { get; set; } = new(); + } + + private readonly string _path; + private readonly Dictionary _profiles = + new(StringComparer.OrdinalIgnoreCase); + + /// + /// is for tests and diagnostics; the app uses + /// . + /// + public VaultProfileStore(string? path = null) + { + _path = string.IsNullOrWhiteSpace(path) + ? Path.Combine(ApplicationPaths.Root, "vaults.json") + : Path.GetFullPath(path); + Load(); + } + + /// Path of the backing file (diagnostics and tests). + public string FilePath => _path; + + /// Number of stored profiles. + public int Count => _profiles.Count; + + /// Every stored profile, ordered by UUID for stable output. + public IReadOnlyList All => + _profiles.Values.OrderBy(profile => profile.Uuid, StringComparer.OrdinalIgnoreCase).ToList(); + + /// The profile for , or null. + public VaultProfile? Get(string? uuid) + { + if (string.IsNullOrWhiteSpace(uuid)) + { + return null; + } + return _profiles.TryGetValue(uuid, out VaultProfile? profile) ? profile : null; + } + + /// + /// Return the profile for this database, creating it from the application + /// defaults when it is opened for the first time. The name is refreshed on + /// every open; the switches are not. + /// + public VaultProfile Ensure(string uuid, string? name, AppSettings defaults) + { + ArgumentException.ThrowIfNullOrWhiteSpace(uuid); + ArgumentNullException.ThrowIfNull(defaults); + if (!_profiles.TryGetValue(uuid, out VaultProfile? profile)) + { + profile = new VaultProfile + { + Uuid = uuid, + SyncOnSave = defaults.SyncOnSave, + BackupRetention = Math.Clamp(defaults.BackupRetention, 1, 200), + }; + _profiles[uuid] = profile; + } + if (!string.IsNullOrWhiteSpace(name)) + { + profile.Name = name; + } + return profile; + } + + /// Store (or replace) a profile as-is. + public void Upsert(VaultProfile profile) + { + ArgumentNullException.ThrowIfNull(profile); + ArgumentException.ThrowIfNullOrWhiteSpace(profile.Uuid); + _profiles[profile.Uuid] = profile; + } + + /// Forget a database. Returns true when something was removed. + public bool Remove(string? uuid) => + !string.IsNullOrWhiteSpace(uuid) && _profiles.Remove(uuid); + + /// Write the file durably; failures are logged, never thrown. + public void Save() + { + var model = new FileModel + { + SchemaVersion = CurrentSchema, + Profiles = All.ToList(), + }; + try + { + byte[] bytes = JsonSerializer.SerializeToUtf8Bytes(model, Options); + AtomicFile.Write(_path, bytes); + } + catch (Exception ex) + { + AppLog.Warn($"could not write {_path}: {ex.Message}"); + } + } + + /// + /// One-time move of the legacy application-wide WebDAV source onto this + /// database. overrides the stored legacy value (the + /// shell may know the source from the recent entry when the settings field + /// was already cleared). Returns true when a source was attached. The legacy + /// fields are cleared afterwards so an old build cannot keep syncing through + /// a hidden mirror (the owner accepted that trade-off). + /// + public static bool MigrateLegacySource( + AppSettings settings, VaultProfileStore store, string uuid, string? name, + string? url = null, string? username = null) + { + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(store); + string? source = string.IsNullOrWhiteSpace(url) ? settings.WebDavUrl : url; + string? sourceUser = string.IsNullOrWhiteSpace(url) ? settings.WebDavUsername : username; + if (string.IsNullOrWhiteSpace(source)) + { + return false; + } + VaultProfile profile = store.Ensure(uuid, name, settings); + if (string.IsNullOrWhiteSpace(profile.WebDavUrl)) + { + profile.WebDavUrl = source; + profile.WebDavUsername = sourceUser; + } + settings.WebDavUrl = null; + settings.WebDavUsername = null; + store.Save(); + return true; + } + + private void Load() + { + if (!File.Exists(_path)) + { + return; + } + try + { + string json = File.ReadAllText(_path); + FileModel? model = JsonSerializer.Deserialize(json, Options); + if (model is null) + { + return; + } + if (model.SchemaVersion > CurrentSchema) + { + AppLog.Warn($"vaults schema {model.SchemaVersion} is newer than supported " + + $"({CurrentSchema}); leaving the file untouched"); + return; + } + foreach (VaultProfile profile in model.Profiles) + { + if (!string.IsNullOrWhiteSpace(profile.Uuid)) + { + _profiles[profile.Uuid] = profile; + } + } + } + catch (Exception ex) + { + // A damaged profile file must not keep the app from starting; the + // vaults themselves are untouched by this file. + AppLog.Warn($"could not read {_path}: {ex.Message}"); + } + } +} diff --git a/apps/windows/Keepassity.Core/VaultRecovery.cs b/apps/windows/Keepassity.Core/VaultRecovery.cs new file mode 100644 index 0000000..7df62b8 --- /dev/null +++ b/apps/windows/Keepassity.Core/VaultRecovery.cs @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +namespace Keepassity.Core; + +/// A local backup plus the bytes that were read from it. +public sealed record RestorableBackup(BackupEntry Entry, byte[] Bytes); + +/// +/// Finds a local backup that can actually replace a database that failed to +/// open. A damaged file still has its pre-save backups next to it, so recovery +/// must not depend on opening the damaged database first (the normal backup list +/// is only reachable once a vault is open). +/// +public static class VaultRecovery +{ + /// + /// Newest backup whose bytes decrypt with the supplied check. Unreadable or + /// corrupt candidates are skipped; returns null when no backup works. + /// + public static async Task FindRestorableBackupAsync( + string databasePath, Func> decrypts, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(decrypts); + foreach (BackupEntry entry in BackupService.ListBackups(databasePath)) + { + cancellationToken.ThrowIfCancellationRequested(); + byte[] bytes; + try + { + bytes = await File.ReadAllBytesAsync(entry.Path, cancellationToken) + .ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // A backup removed or locked between listing and reading is not a + // recovery candidate; the next older one may still work. + continue; + } + bool usable; + try + { + usable = await decrypts(bytes).ConfigureAwait(false); + } + catch (CoreException) + { + // The candidate does not decrypt with the current password. + usable = false; + } + if (usable) + { + return new RestorableBackup(entry, bytes); + } + } + return null; + } +} diff --git a/apps/windows/Keepassity.Core/VaultSession.cs b/apps/windows/Keepassity.Core/VaultSession.cs new file mode 100644 index 0000000..554639b --- /dev/null +++ b/apps/windows/Keepassity.Core/VaultSession.cs @@ -0,0 +1,344 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +namespace Keepassity.Core; + +/// +/// The single-writer guard for one vault. A password manager has three ways to +/// lose data on write, and this class makes the window apply all three +/// consistently instead of composing them at each call site: +/// +/// +/// a cross-process , so two Keepassity windows +/// cannot own the same database; +/// an in-process , so an older async snapshot +/// cannot land after a newer one; +/// a of the bytes the model came from, so a +/// file changed by another program is refused instead of overwritten. +/// +/// +/// Saves, sync replacements and backup restores all go through here. The caller +/// still owns opening the core and refreshing the UI around it. +/// +public sealed class VaultSession : IDisposable +{ + private readonly VaultWriteGate _writes = new(); + private readonly object _writeStateSync = new(); + private VaultFileLock? _lock; + private VaultFingerprint? _fingerprint; + private string? _fingerprintPath; + private int _activeWrites; + private TaskCompletionSource? _writesIdle; + + /// Absolute path of the acquired vault, or null before/after a release. + public string? DatabasePath { get; private set; } + + /// + /// Take the exclusive lock for and remember it + /// as the current database. Re-acquiring the current path keeps the lock. + /// Returns false with when another window owns the + /// vault (or the lock file cannot be created). + /// + public bool TryAcquire(string databasePath, out string? error) + { + error = null; + string fullPath; + try + { + fullPath = Path.GetFullPath(databasePath); + } + catch (Exception ex) + { + error = ex.Message; + return false; + } + if (_lock is not null && string.Equals(_lock.DatabasePath, fullPath, + StringComparison.OrdinalIgnoreCase)) + { + return true; + } + // Keep at most one lock: switching databases releases the previous vault. + _lock?.Dispose(); + _lock = null; + DatabasePath = null; + _lock = VaultFileLock.TryAcquire(fullPath, out error); + if (_lock is null) + { + return false; + } + DatabasePath = fullPath; + return true; + } + + /// Drop the lock and the fingerprint. The session can be reused. + public void Release() + { + _lock?.Dispose(); + _lock = null; + DatabasePath = null; + _fingerprint = null; + _fingerprintPath = null; + } + + /// + /// Remember the bytes the open model came from. Call after opening the vault, + /// after every successful write and after a WebDAV download is promoted. + /// + public void CaptureFingerprint(string? databasePath = null) + { + string? path = databasePath ?? DatabasePath; + _fingerprint = null; + _fingerprintPath = null; + if (path is null || !File.Exists(path)) + { + return; + } + try + { + _fingerprint = VaultFingerprint.Capture(path); + _fingerprintPath = Path.GetFullPath(path); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + AppLog.Warn($"cannot fingerprint the database: {ex.Message}"); + } + } + + /// + /// True when the file on disk no longer matches the bytes the model came + /// from. A missing or unreadable file also counts as changed, so a save + /// cannot recreate a file another program moved. Without a captured + /// fingerprint there is nothing to compare and this returns false. + /// + public bool ChangedOnDisk(string? databasePath = null) + { + if (_fingerprint is not VaultFingerprint expected) + { + return false; + } + string? path = databasePath ?? _fingerprintPath ?? DatabasePath; + if (path is null || !File.Exists(path)) + { + return true; + } + try + { + return !VaultFingerprint.Capture(path).Matches(expected); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return true; + } + } + + /// + /// True while a save, sync replacement or restore is queued or running. The + /// shell uses this to drain in-flight writes before the process exits, so an + /// edit that is already being written is not cut off by shutdown. + /// + public bool IsWriting + { + get + { + lock (_writeStateSync) + { + return _activeWrites > 0; + } + } + } + + /// + /// Wait until no write is queued or running. Returns when the vault is idle + /// or when elapses; the caller may close anyway + /// then, because the durable protocol always leaves the last complete file. + /// + public async Task WaitForIdleAsync(TimeSpan timeout, + CancellationToken cancellationToken = default) + { + using var timeoutSource = new CancellationTokenSource(timeout); + using var linked = CancellationTokenSource.CreateLinkedTokenSource( + cancellationToken, timeoutSource.Token); + while (true) + { + Task idle; + lock (_writeStateSync) + { + if (_activeWrites == 0) + { + return; + } + _writesIdle ??= + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + idle = _writesIdle.Task; + } + try + { + await idle.WaitAsync(linked.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + when (timeoutSource.IsCancellationRequested && + !cancellationToken.IsCancellationRequested) + { + // The shell closes after the bounded wait; the file is either + // the previous or the next complete database, never a partial one. + return; + } + } + } + + /// + /// Read the database bytes through the same gate that serializes writes. + /// Without this a sync can hold the file open exactly while a save replaces + /// it, and Windows then fails the replace with a sharing violation; reading + /// under the gate means sync always sees a complete database and the save + /// never collides with it. Counted as an operation for the shutdown drain. + /// + public async Task ReadBytesAsync(CancellationToken cancellationToken = default) + { + BeginWrite(); + try + { + string path = AcquiredPath(); + using IDisposable read = await _writes.EnterAsync().ConfigureAwait(false); + return await File.ReadAllBytesAsync(path, cancellationToken) + .ConfigureAwait(false); + } + finally + { + EndWrite(); + } + } + + /// + /// Save the open model through : wait for the write + /// gate, refuse when the file changed outside the application (checked once + /// here and once more after serialization by the core), then remember the + /// new bytes. Throws with code VaultChanged + /// when the save was refused. + /// + public async Task SaveAsync(ICoreClient core, int backupRetention = 20) + { + ArgumentNullException.ThrowIfNull(core); + BeginWrite(); + try + { + string path = AcquiredPath(); + using IDisposable write = await _writes.EnterAsync().ConfigureAwait(false); + EnsureUnchanged(path); + await core.SaveAsync(path, backupRetention, () => ChangedOnDisk(path)) + .ConfigureAwait(false); + CaptureFingerprint(path); + } + finally + { + EndWrite(); + } + } + + /// + /// Replace the open vault with already verified bytes (sync download or + /// merge) using the durable write protocol, including a backup. + /// + public async Task ReplaceAsync(byte[] bytes, int backupRetention = 20, + string reason = "sync") + { + BeginWrite(); + try + { + string path = AcquiredPath(); + using IDisposable write = await _writes.EnterAsync().ConfigureAwait(false); + EnsureUnchanged(path); + await Task.Run(() => AtomicFile.Replace(path, bytes, backupRetention, reason, + () => ChangedOnDisk(path))) + .ConfigureAwait(false); + CaptureFingerprint(path); + } + finally + { + EndWrite(); + } + } + + /// + /// Replace the open vault with backup bytes: the current file is copied to + /// the backup area first, then replaced atomically. + /// runs inside the write gate, which is where reopening the core from the + /// restored bytes belongs. + /// + public async Task RestoreAsync(byte[] content, int backupRetention = 20, + Func? afterReplace = null) + { + BeginWrite(); + try + { + string path = AcquiredPath(); + using IDisposable write = await _writes.EnterAsync().ConfigureAwait(false); + EnsureUnchanged(path); + await Task.Run(() => BackupService.RestoreBytes(path, content, backupRetention, + () => ChangedOnDisk(path))) + .ConfigureAwait(false); + if (afterReplace is not null) + { + await afterReplace().ConfigureAwait(false); + } + CaptureFingerprint(path); + } + finally + { + EndWrite(); + } + } + + /// Release the lock and dispose the write gate. + public void Dispose() + { + Release(); + lock (_writeStateSync) + { + if (_activeWrites > 0) + { + // A writer is still in flight after the shutdown drain timeout. + // Leave the gate alive for it; the process is exiting and the + // durable protocol keeps the file whole. + AppLog.Warn("vault session disposed with a write still in flight"); + return; + } + } + _writes.Dispose(); + } + + private string AcquiredPath() => DatabasePath ?? + throw new InvalidOperationException("no vault is acquired"); + + private void BeginWrite() + { + lock (_writeStateSync) + { + _activeWrites++; + } + } + + private void EndWrite() + { + TaskCompletionSource? idle = null; + lock (_writeStateSync) + { + _activeWrites--; + if (_activeWrites == 0) + { + idle = _writesIdle; + _writesIdle = null; + } + } + idle?.TrySetResult(); + } + + private void EnsureUnchanged(string path) + { + if (!ChangedOnDisk(path)) + { + return; + } + AppLog.Warn("vault write refused: the database changed outside this window"); + throw new CoreException("VaultChanged", + "the database changed outside this application; nothing was overwritten"); + } +} diff --git a/apps/windows/Keepassity.Core/VaultWriteGate.cs b/apps/windows/Keepassity.Core/VaultWriteGate.cs new file mode 100644 index 0000000..65aecc5 --- /dev/null +++ b/apps/windows/Keepassity.Core/VaultWriteGate.cs @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +namespace Keepassity.Core; + +/// +/// Serializes operations that replace the live vault file inside one process. +/// The cross-process vault lock stops two windows, but an async UI can still +/// start a second save/sync write before the first one reaches the atomic +/// replace; without this gate a slower, older snapshot could land last. +/// +public sealed class VaultWriteGate : IDisposable +{ + private readonly SemaphoreSlim _gate = new(1, 1); + + /// Wait until no other vault write is in progress. + public async Task EnterAsync(CancellationToken cancellationToken = default) + { + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + return new Releaser(_gate); + } + + public void Dispose() => _gate.Dispose(); + + private sealed class Releaser : IDisposable + { + private SemaphoreSlim? _gate; + + public Releaser(SemaphoreSlim gate) => _gate = gate; + + public void Dispose() + { + Interlocked.Exchange(ref _gate, null)?.Release(); + } + } +} diff --git a/apps/windows/Keepassity.Core/WebDavClient.cs b/apps/windows/Keepassity.Core/WebDavClient.cs index f9e94cb..919628c 100644 --- a/apps/windows/Keepassity.Core/WebDavClient.cs +++ b/apps/windows/Keepassity.Core/WebDavClient.cs @@ -7,7 +7,7 @@ using System.Text; using System.Xml.Linq; -namespace Keepassity.Mock; +namespace Keepassity.Core; public class WebDavException : Exception { @@ -30,7 +30,7 @@ public sealed class WebDavFileInfo } /// Minimal WebDAV file client: PROPFIND depth 0, GET and conditional PUT. -public sealed class WebDavClient : IDisposable +public sealed class WebDavClient : IDisposable, ISyncRemote { private const string PropfindBody = "" + @@ -38,27 +38,82 @@ public sealed class WebDavClient : IDisposable ""; private readonly HttpClient _client; + /// + /// Uploads never follow redirects: a 301/302/303/307/308 would otherwise be + /// replayed as a body-less GET (303) and a 200 response from the redirect + /// target would look like a successful database upload. + /// + private readonly HttpClient _uploadClient; private readonly Uri _fileUri; + private readonly TimeSpan _metadataTimeout; + private readonly TimeSpan _transferTimeout; + + /// PROPFIND is a small request; a short timeout keeps sync responsive. + public static readonly TimeSpan DefaultMetadataTimeout = TimeSpan.FromSeconds(45); + + /// + /// Download/upload carry the whole database, which can hold large attachments; + /// the old fixed 45-second client timeout made big vaults on slow links fail + /// every save. A stalled transfer still ends after half an hour. + /// + public static readonly TimeSpan DefaultTransferTimeout = TimeSpan.FromMinutes(30); /// /// Lowercase hex SHA-256 of a certificate the user explicitly trusted (SY-04). /// Only that exact certificate is accepted in addition to the platform-trusted /// chain; certificate validation is never disabled globally. /// + /// Override for tests; defaults to + /// . + /// Override for tests; defaults to + /// . public WebDavClient(string fileUrl, string username, string password, - string? trustedCertificateSha256 = null) + string? trustedCertificateSha256 = null, TimeSpan? metadataTimeout = null, + TimeSpan? transferTimeout = null) { if (!Uri.TryCreate(fileUrl, UriKind.Absolute, out Uri? uri) || (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)) { throw new WebDavException("WebDAV URL must be an absolute http(s) file URL."); } + if (uri.Scheme == Uri.UriSchemeHttp && !uri.IsLoopback) + { + // Basic authentication sends the WebDAV password with every + // request, so plain HTTP is only acceptable for loopback tests. + throw new WebDavException( + "WebDAV URLs must use https:// (the password travels with Basic authentication)."); + } _fileUri = uri; + _metadataTimeout = metadataTimeout ?? DefaultMetadataTimeout; + _transferTimeout = transferTimeout ?? DefaultTransferTimeout; + _client = CreateHttpClient(username, password, trustedCertificateSha256, + // Download and metadata must not follow redirects either: a redirected + // host could receive Basic credentials, and a redirected GET could + // replace the working copy with a different resource. The upload + // client already rejects redirects; both paths fail closed. + allowAutoRedirect: false); + _uploadClient = CreateHttpClient(username, password, trustedCertificateSha256, + allowAutoRedirect: false); + } + + /// Timeout for one request; caller cancellation still wins. + private static CancellationTokenSource StartTimeout(CancellationToken cancellationToken, + TimeSpan timeout) + { + CancellationTokenSource cts = + CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(timeout); + return cts; + } + + private static HttpClient CreateHttpClient(string username, string password, + string? trustedCertificateSha256, bool allowAutoRedirect) + { var handler = new HttpClientHandler { Credentials = new NetworkCredential(username, password), PreAuthenticate = true, - AllowAutoRedirect = true, + AllowAutoRedirect = allowAutoRedirect, }; if (!string.IsNullOrWhiteSpace(trustedCertificateSha256)) { @@ -69,35 +124,40 @@ public WebDavClient(string fileUrl, string username, string password, string.Equals(WebDavTls.Fingerprint(certificate), pinned, StringComparison.Ordinal)); } - _client = new HttpClient(handler) + var client = new HttpClient(handler) { - Timeout = TimeSpan.FromSeconds(45), + // Per-operation timeouts are applied by the caller so a large vault + // upload is not capped at the metadata request's short timeout. + Timeout = Timeout.InfiniteTimeSpan, }; // Update together with Directory.Build.props on a release bump. - _client.DefaultRequestHeaders.UserAgent.ParseAdd("keepassity/1.0.0"); + client.DefaultRequestHeaders.UserAgent.ParseAdd("keepassity/1.0.0"); if (!string.IsNullOrEmpty(username)) { string token = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}")); - _client.DefaultRequestHeaders.Authorization = + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token); } + return client; } public async Task GetMetadataAsync(CancellationToken cancellationToken = default) { try { + using var timeout = StartTimeout(cancellationToken, _metadataTimeout); + CancellationToken token = timeout.Token; using var request = new HttpRequestMessage(new HttpMethod("PROPFIND"), _fileUri); request.Headers.TryAddWithoutValidation("Depth", "0"); request.Content = new StringContent(PropfindBody, Encoding.UTF8, "application/xml"); using HttpResponseMessage response = await _client.SendAsync(request, - HttpCompletionOption.ResponseContentRead, cancellationToken); + HttpCompletionOption.ResponseContentRead, token); if (response.StatusCode == HttpStatusCode.NotFound) { return null; } - await EnsureSuccessAsync(response, cancellationToken); - string text = await response.Content.ReadAsStringAsync(cancellationToken); + await EnsureSuccessAsync(response, token); + string text = await response.Content.ReadAsStringAsync(token); XNamespace dav = "DAV:"; XElement? prop = XDocument.Parse(text) .Descendants(dav + "response") @@ -128,26 +188,38 @@ public WebDavClient(string fileUrl, string username, string password, { throw new WebDavTlsException(_fileUri, tls); } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + throw new WebDavException("The WebDAV metadata request timed out."); + } } public async Task DownloadAsync(CancellationToken cancellationToken = default) { try { + using var timeout = StartTimeout(cancellationToken, _transferTimeout); + CancellationToken token = timeout.Token; using HttpResponseMessage response = await _client.GetAsync(_fileUri, - HttpCompletionOption.ResponseContentRead, cancellationToken); - await EnsureSuccessAsync(response, cancellationToken); - return await response.Content.ReadAsByteArrayAsync(cancellationToken); + HttpCompletionOption.ResponseHeadersRead, token); + await EnsureSuccessAsync(response, token); + return await response.Content.ReadAsByteArrayAsync(token); } catch (HttpRequestException ex) when (ex.InnerException is AuthenticationException tls) { throw new WebDavTlsException(_fileUri, tls); } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + throw new WebDavException("The WebDAV download timed out."); + } } public async Task UploadAsync(byte[] bytes, string? ifMatch, CancellationToken cancellationToken = default) { + using var timeout = StartTimeout(cancellationToken, _transferTimeout); + CancellationToken token = timeout.Token; using var request = new HttpRequestMessage(HttpMethod.Put, _fileUri); var content = new ByteArrayContent(bytes); content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); @@ -163,13 +235,17 @@ public async Task DownloadAsync(CancellationToken cancellationToken = de HttpResponseMessage response; try { - response = await _client.SendAsync(request, - HttpCompletionOption.ResponseHeadersRead, cancellationToken); + response = await _uploadClient.SendAsync(request, + HttpCompletionOption.ResponseHeadersRead, token); } catch (HttpRequestException ex) when (ex.InnerException is AuthenticationException tls) { throw new WebDavTlsException(_fileUri, tls); } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + throw new WebDavException("The WebDAV upload timed out."); + } using (response) { if (response.StatusCode == HttpStatusCode.PreconditionFailed) @@ -177,11 +253,28 @@ public async Task DownloadAsync(CancellationToken cancellationToken = de throw new WebDavException("The remote database changed during sync.", 412, conflict: true); } - await EnsureSuccessAsync(response, cancellationToken); - return response.Headers.ETag?.Tag + await EnsureSuccessAsync(response, token); + string? uploadedEtag = response.Headers.ETag?.Tag ?? (response.Headers.TryGetValues("ETag", out IEnumerable? values) ? values.FirstOrDefault()?.Trim() : null); + // A proxy or a server that cuts the request short can answer 2xx while + // storing fewer bytes. Confirm the size before this upload can become the + // recorded baseline; a truncated remote is then caught here instead of on + // the next download. + WebDavFileInfo? stored = await GetMetadataAsync(token); + if (stored is null) + { + throw new WebDavException( + "The WebDAV server did not keep the uploaded file."); + } + if (stored.Size != bytes.LongLength) + { + throw new WebDavException( + $"The WebDAV server stored {stored.Size} byte(s) instead of " + + $"{bytes.LongLength}; the upload was incomplete."); + } + return uploadedEtag ?? stored.ETag; } } @@ -209,6 +302,10 @@ private static async Task EnsureSuccessAsync(HttpResponseMessage response, HttpStatusCode.MethodNotAllowed => "The WebDAV server rejected the required method.", HttpStatusCode.InsufficientStorage => "The WebDAV server is out of storage.", HttpStatusCode.Conflict => "The remote path conflicts with a collection.", + HttpStatusCode.MovedPermanently or HttpStatusCode.Found or + HttpStatusCode.SeeOther or HttpStatusCode.TemporaryRedirect or + HttpStatusCode.PermanentRedirect => + "The WebDAV server redirected the request; refusing to follow it.", _ => $"WebDAV request failed ({(int)response.StatusCode} {response.ReasonPhrase}).", }; if (body.Length is > 0 and < 500) @@ -218,5 +315,9 @@ private static async Task EnsureSuccessAsync(HttpResponseMessage response, throw new WebDavException(message, (int)response.StatusCode); } - public void Dispose() => _client.Dispose(); + public void Dispose() + { + _client.Dispose(); + _uploadClient.Dispose(); + } } diff --git a/apps/windows/Keepassity.Core/WebDavTls.cs b/apps/windows/Keepassity.Core/WebDavTls.cs index e88c3ef..77e3a3c 100644 --- a/apps/windows/Keepassity.Core/WebDavTls.cs +++ b/apps/windows/Keepassity.Core/WebDavTls.cs @@ -5,7 +5,7 @@ using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; -namespace Keepassity.Mock; +namespace Keepassity.Core; /// /// Facts about the TLS certificate a WebDAV server presents, shown to the user diff --git a/apps/windows/Keepassity.Core/packages.lock.json b/apps/windows/Keepassity.Core/packages.lock.json deleted file mode 100644 index 6c13474..0000000 --- a/apps/windows/Keepassity.Core/packages.lock.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "version": 2, - "dependencies": { - "net8.0": {}, - "net8.0/win-x64": {} - } -} \ No newline at end of file diff --git a/apps/windows/Keepassity.Mock/App.xaml b/apps/windows/Keepassity.Mock/App.xaml deleted file mode 100644 index 22e4fff..0000000 --- a/apps/windows/Keepassity.Mock/App.xaml +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - - - - - 0 - 0 - - - - - - - - - - diff --git a/apps/windows/Keepassity.Mock/CoreClient.cs b/apps/windows/Keepassity.Mock/CoreClient.cs deleted file mode 100644 index 70448da..0000000 --- a/apps/windows/Keepassity.Mock/CoreClient.cs +++ /dev/null @@ -1,724 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-or-later -// Thin P/Invoke wrapper around the keepassity FFI v1 contract. -using System.Runtime.InteropServices; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace Keepassity.Mock; - -public sealed class CoreException : Exception -{ - public CoreException(string code, string message) : base($"{code}: {message}") - { - Code = code; - } - - public string Code { get; } -} - -public sealed class CoreClient : IDisposable -{ - private const string Library = "keepassity_ffi"; - private static readonly JsonSerializerOptions JsonOptions = new() - { - PropertyNameCaseInsensitive = true, - }; - - private readonly SemaphoreSlim _gate = new(1, 1); - private IntPtr _handle; - - public bool IsOpen => _handle != IntPtr.Zero; - public string? DatabasePath { get; private set; } - - [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] - private static extern uint kp_api_version(); - - [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] - private static extern IntPtr kp_last_error_json(); - - [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] - private static extern IntPtr kp_open(byte[] kdbx, UIntPtr len, byte[] optsJson); - - [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] - private static extern int kp_lock(IntPtr handle); - - [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] - private static extern int kp_close(IntPtr handle); - - [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] - private static extern int kp_call(IntPtr handle, byte[] commandJson, out IntPtr outJson); - - [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] - private static extern int kp_save(IntPtr handle, out IntPtr outBytes, out UIntPtr outLen); - - [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] - private static extern int kp_create_database(byte[] optsJson, out IntPtr outBytes, - out UIntPtr outLen); - - [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] - private static extern int kp_sync_decide(IntPtr handle, byte[] remoteMetaJson, - int localDirty, out IntPtr outJson); - - [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] - private static extern int kp_sync_merge(IntPtr handle, byte[] remote, UIntPtr len, - out IntPtr outBytes, out UIntPtr outLen, out IntPtr conflictsJson); - - [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] - private static extern int kp_sync_commit(IntPtr handle, IntPtr etag, IntPtr sha256); - - [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] - private static extern void kp_string_free(IntPtr value); - - [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] - private static extern void kp_buffer_free(IntPtr value, UIntPtr len); - - public async Task OpenAsync(string path, string password) - { - byte[] bytes = await File.ReadAllBytesAsync(path).ConfigureAwait(false); - await _gate.WaitAsync().ConfigureAwait(false); - try - { - CloseHandleLocked(); - await Task.Run(() => - { - string error = LastError(); - if (kp_api_version() != 1) - { - throw new CoreException("VersionMismatch", - $"FFI major version {kp_api_version()} is not supported (expected 1)."); - } - byte[] options = Utf8Z(JsonSerializer.Serialize(new { password })); - IntPtr handle = kp_open(bytes, (UIntPtr)bytes.LongLength, options); - if (handle == IntPtr.Zero) - { - error = LastError(); - throw ParseError(error, "open database"); - } - _handle = handle; - }).ConfigureAwait(false); - DatabasePath = path; - } - finally - { - _gate.Release(); - } - } - - public async Task CreateDatabaseAsync(string name, string password) - { - await _gate.WaitAsync().ConfigureAwait(false); - try - { - return await Task.Run(() => - { - byte[] options = Utf8Z(JsonSerializer.Serialize(new { name, password })); - if (kp_create_database(options, out IntPtr pointer, out UIntPtr length) != 0 || - pointer == IntPtr.Zero) - { - throw ParseError(LastError(), "create database"); - } - try - { - var bytes = new byte[checked((int)length.ToUInt64())]; - Marshal.Copy(pointer, bytes, 0, bytes.Length); - return bytes; - } - finally - { - kp_buffer_free(pointer, length); - } - }).ConfigureAwait(false); - } - finally - { - _gate.Release(); - } - } - - public async Task> ListGroupsAsync() - => await CallAsync>("{\"command\":\"list_groups\"}") - .ConfigureAwait(false); - - public async Task CreateGroupAsync(string parentUuid, string name) - { - string command = JsonSerializer.Serialize(new - { - command = "create_group", - parent_uuid = parentUuid, - name, - }); - CreateGroupResponse response = await CallAsync(command) - .ConfigureAwait(false); - return response.Uuid; - } - - public async Task RenameGroupAsync(string uuid, string name) - => _ = await CallAsync(JsonSerializer.Serialize(new - { - command = "rename_group", - uuid, - name, - })).ConfigureAwait(false); - - public async Task DeleteGroupAsync(string uuid) - => _ = await CallAsync(JsonSerializer.Serialize(new - { - command = "delete_group", - uuid, - })).ConfigureAwait(false); - - public async Task> ListEntriesAsync(string? groupUuid = null) - { - string command = groupUuid is null - ? "{\"command\":\"list_entries\",\"include_subgroups\":true}" - : JsonSerializer.Serialize(new - { - command = "list_entries", - group_uuid = groupUuid, - include_subgroups = true, - }); - return await CallAsync>(command).ConfigureAwait(false); - } - - public async Task GetEntryAsync(string uuid) - => await CallAsync(JsonSerializer.Serialize(new - { - command = "get_entry", - uuid, - })).ConfigureAwait(false); - - public async Task> SearchAsync(string query) - { - string command = JsonSerializer.Serialize(new - { - command = "search", - query, - limit = 200, - }); - SearchResponseDto response = await CallAsync(command).ConfigureAwait(false); - return response.Matches; - } - - public async Task CreateEntryAsync(string groupUuid, string title, string username, - string password, string url, string notes) - { - string command = JsonSerializer.Serialize(new - { - command = "create_entry", - group_uuid = groupUuid, - fields = new Dictionary - { - ["Title"] = title, - ["UserName"] = username, - ["Password"] = password, - ["URL"] = url, - ["Notes"] = notes, - }, - }); - CreateEntryResponse response = await CallAsync(command) - .ConfigureAwait(false); - return response.Uuid; - } - - public async Task UpdateEntryAsync(string uuid, string title, string username, - string password, string url, string notes, IReadOnlyList tags) - { - string command = JsonSerializer.Serialize(new - { - command = "update_entry", - uuid, - patch = new Dictionary - { - ["Title"] = title, - ["UserName"] = username, - ["Password"] = password, - ["URL"] = url, - ["Notes"] = notes, - ["tags"] = tags, - }, - }); - _ = await CallAsync(command).ConfigureAwait(false); - } - - public async Task DeleteEntryAsync(string uuid) - => _ = await CallAsync(JsonSerializer.Serialize(new - { - command = "delete_entry", - uuid, - permanent = false, - })).ConfigureAwait(false); - - public async Task MoveEntryAsync(string uuid, string groupUuid) - => _ = await CallAsync(JsonSerializer.Serialize(new - { - command = "move_entry", - uuid, - group_uuid = groupUuid, - })).ConfigureAwait(false); - - /// - /// Generates a one-time password code. Pass to - /// compute the code for a specific Unix second (used to pre-fetch the next - /// TOTP window); null asks the core for the current window. - /// - public async Task TotpCodeAsync(string uuid, long? atUnix = null) - { - try - { - string command = atUnix is null - ? JsonSerializer.Serialize(new - { - command = "totp_code", - uuid, - }) - : JsonSerializer.Serialize(new - { - command = "totp_code", - uuid, - at_unix = Math.Max(0, atUnix.Value), - }); - return await CallAsync(command).ConfigureAwait(false); - } - catch (CoreException ex) when (ex.Code == "NotFound") - { - return null; - } - } - - public async Task ParseTotpUriAsync(string uri) - => await CallAsync(JsonSerializer.Serialize(new - { - command = "totp_parse_uri", - uri, - })).ConfigureAwait(false); - - public async Task TotpSetAsync(string uuid, TotpConfigDto config) - => _ = await CallAsync(JsonSerializer.Serialize(new - { - command = "totp_set", - uuid, - config, - })).ConfigureAwait(false); - - public async Task TotpDeleteAsync(string uuid) - => _ = await CallAsync(JsonSerializer.Serialize(new - { - command = "totp_delete", - uuid, - })).ConfigureAwait(false); - - /// - /// Generates a random password through the core. The character classes are - /// passed to the core so entropy matches the actual alphabet; symbols stay - /// comma/quote free so the result is safe in every password box. - /// - public async Task GeneratePasswordAsync(int length = 20, - bool excludeAmbiguous = true, bool lowercase = true, bool uppercase = true, - bool digits = true, bool symbols = true) - => await CallAsync(JsonSerializer.Serialize(new - { - command = "password_generate", - length = Math.Clamp(length, 1, 256), - classes = new - { - lowercase, - uppercase, - digits, - symbols, - }, - exclude_ambiguous = excludeAmbiguous, - })).ConfigureAwait(false); - - public async Task SaveBytesAsync() - { - await _gate.WaitAsync().ConfigureAwait(false); - try - { - EnsureOpen(); - return await Task.Run(() => - { - if (kp_save(_handle, out IntPtr pointer, out UIntPtr length) != 0 || - pointer == IntPtr.Zero) - { - throw ParseError(LastError(), "save database"); - } - try - { - var result = new byte[checked((int)length.ToUInt64())]; - Marshal.Copy(pointer, result, 0, result.Length); - return result; - } - finally - { - kp_buffer_free(pointer, length); - } - }).ConfigureAwait(false); - } - finally - { - _gate.Release(); - } - } - - public async Task SaveAsync(string path, int backupRetention = 20) - { - byte[] bytes = await SaveBytesAsync().ConfigureAwait(false); - string directory = Path.GetDirectoryName(Path.GetFullPath(path))!; - Directory.CreateDirectory(directory); - string temp = Path.Combine(directory, - $".{Path.GetFileName(path)}.keepassity-tmp-{Guid.NewGuid():N}"); - await File.WriteAllBytesAsync(temp, bytes).ConfigureAwait(false); - if (File.Exists(path)) - { - BackupService.CreateBackup(path, backupRetention, "save"); - File.Replace(temp, path, path + ".keepassity-bak", true); - } - else - { - File.Move(temp, path); - } - DatabasePath = path; - } - - public async Task SyncDecideAsync(string remoteMetaJson, bool localDirty) - { - await _gate.WaitAsync().ConfigureAwait(false); - try - { - EnsureOpen(); - return await Task.Run(() => - { - if (kp_sync_decide(_handle, Utf8Z(remoteMetaJson), localDirty ? 1 : 0, - out IntPtr output) != 0 || output == IntPtr.Zero) - { - throw ParseError(LastError(), "sync decide"); - } - try - { - string json = Marshal.PtrToStringUTF8(output) - ?? throw new CoreException("Internal", "sync decide returned null."); - return JsonSerializer.Deserialize(json, JsonOptions) - ?? throw new CoreException("Internal", "sync decide returned empty JSON."); - } - finally - { - kp_string_free(output); - } - }).ConfigureAwait(false); - } - finally - { - _gate.Release(); - } - } - - public async Task SyncMergeAsync(byte[] remote) - { - await _gate.WaitAsync().ConfigureAwait(false); - try - { - EnsureOpen(); - return await Task.Run(() => - { - if (kp_sync_merge(_handle, remote, (UIntPtr)remote.LongLength, - out IntPtr bytesPointer, out UIntPtr bytesLength, - out IntPtr conflictsPointer) != 0 || - bytesPointer == IntPtr.Zero || conflictsPointer == IntPtr.Zero) - { - throw ParseError(LastError(), "sync merge"); - } - try - { - var bytes = new byte[checked((int)bytesLength.ToUInt64())]; - Marshal.Copy(bytesPointer, bytes, 0, bytes.Length); - string conflictsJson = Marshal.PtrToStringUTF8(conflictsPointer) - ?? "[]"; - List conflicts = JsonSerializer.Deserialize>( - conflictsJson, JsonOptions) ?? new List(); - return new SyncMergeResult(bytes, conflicts); - } - finally - { - kp_buffer_free(bytesPointer, bytesLength); - kp_string_free(conflictsPointer); - } - }).ConfigureAwait(false); - } - finally - { - _gate.Release(); - } - } - - public async Task SyncCommitAsync(string? etag, string? sha256) - { - await _gate.WaitAsync().ConfigureAwait(false); - try - { - EnsureOpen(); - await Task.Run(() => - { - IntPtr etagPointer = IntPtr.Zero; - IntPtr shaPointer = IntPtr.Zero; - try - { - if (etag is not null) - { - etagPointer = Marshal.StringToCoTaskMemUTF8(etag); - } - if (sha256 is not null) - { - shaPointer = Marshal.StringToCoTaskMemUTF8(sha256); - } - if (kp_sync_commit(_handle, etagPointer, shaPointer) != 0) - { - throw ParseError(LastError(), "sync commit"); - } - } - finally - { - if (etagPointer != IntPtr.Zero) - { - Marshal.FreeCoTaskMem(etagPointer); - } - if (shaPointer != IntPtr.Zero) - { - Marshal.FreeCoTaskMem(shaPointer); - } - } - }).ConfigureAwait(false); - } - finally - { - _gate.Release(); - } - } - - public async Task LockAsync() - { - await _gate.WaitAsync().ConfigureAwait(false); - try - { - if (_handle != IntPtr.Zero) - { - _ = kp_lock(_handle); - } - } - finally - { - _gate.Release(); - } - } - - public void Dispose() - { - _gate.Wait(); - try - { - CloseHandleLocked(); - } - finally - { - _gate.Release(); - _gate.Dispose(); - } - } - - private void CloseHandleLocked() - { - if (_handle == IntPtr.Zero) - { - return; - } - _ = kp_close(_handle); - _handle = IntPtr.Zero; - } - - private async Task CallAsync(string command) - { - await _gate.WaitAsync().ConfigureAwait(false); - try - { - EnsureOpen(); - return await Task.Run(() => - { - byte[] input = Utf8Z(command); - if (kp_call(_handle, input, out IntPtr output) != 0 || output == IntPtr.Zero) - { - throw ParseError(LastError(), command); - } - try - { - string json = Marshal.PtrToStringUTF8(output) - ?? throw new CoreException("Internal", "FFI returned null JSON."); - return JsonSerializer.Deserialize(json, JsonOptions) - ?? throw new CoreException("Internal", "FFI returned empty JSON."); - } - finally - { - kp_string_free(output); - } - }).ConfigureAwait(false); - } - finally - { - _gate.Release(); - } - } - - private void EnsureOpen() - { - if (_handle == IntPtr.Zero) - { - throw new CoreException("Locked", "database is locked"); - } - } - - private static byte[] Utf8Z(string value) => Encoding.UTF8.GetBytes(value + "\0"); - - private static CoreException ParseError(string json, string operation) - { - try - { - ErrorDto? error = JsonSerializer.Deserialize(json, JsonOptions); - return new CoreException(error?.Code ?? "Internal", - error?.Message ?? $"{operation} failed."); - } - catch (JsonException) - { - return new CoreException("Internal", $"{operation} failed: {json}"); - } - } - - private static string LastError() - { - IntPtr pointer = kp_last_error_json(); - return pointer == IntPtr.Zero - ? "{\"code\":\"Internal\",\"message\":\"no error details\"}" - : Marshal.PtrToStringUTF8(pointer) ?? "{\"code\":\"Internal\",\"message\":\"null error\"}"; - } -} - -public sealed class GroupDto -{ - [JsonPropertyName("uuid")] public string Uuid { get; set; } = ""; - [JsonPropertyName("parent_uuid")] public string? ParentUuid { get; set; } - [JsonPropertyName("name")] public string Name { get; set; } = ""; - [JsonPropertyName("icon")] public int Icon { get; set; } - [JsonPropertyName("order")] public int Order { get; set; } -} - -public sealed class EntrySummaryDto -{ - [JsonPropertyName("uuid")] public string Uuid { get; set; } = ""; - [JsonPropertyName("title")] public string Title { get; set; } = ""; - [JsonPropertyName("username")] public string Username { get; set; } = ""; - [JsonPropertyName("url")] public string Url { get; set; } = ""; - [JsonPropertyName("group_uuid")] public string GroupUuid { get; set; } = ""; - [JsonPropertyName("has_totp")] public bool HasTotp { get; set; } - [JsonPropertyName("modified_unix")] public long ModifiedUnix { get; set; } -} - -public sealed class EntryFullDto -{ - [JsonPropertyName("uuid")] public string Uuid { get; set; } = ""; - [JsonPropertyName("group_uuid")] public string GroupUuid { get; set; } = ""; - [JsonPropertyName("title")] public string Title { get; set; } = ""; - [JsonPropertyName("username")] public string Username { get; set; } = ""; - [JsonPropertyName("password_secret")] public string PasswordSecret { get; set; } = ""; - [JsonPropertyName("url")] public string Url { get; set; } = ""; - [JsonPropertyName("notes")] public string Notes { get; set; } = ""; - [JsonPropertyName("tags")] public List Tags { get; set; } = new(); - [JsonPropertyName("custom_fields")] public List CustomFields { get; set; } = new(); - [JsonPropertyName("times")] public TimesDto Times { get; set; } = new(); - [JsonPropertyName("history_count")] public int HistoryCount { get; set; } - [JsonPropertyName("totp")] public TotpConfigDto? Totp { get; set; } -} - -public sealed class CustomFieldDto -{ - [JsonPropertyName("key")] public string Key { get; set; } = ""; - [JsonPropertyName("value")] public string Value { get; set; } = ""; - [JsonPropertyName("protected")] public bool Protected { get; set; } -} - -public sealed class TimesDto -{ - [JsonPropertyName("created_unix")] public long? CreatedUnix { get; set; } - [JsonPropertyName("modified_unix")] public long? ModifiedUnix { get; set; } -} - -public sealed class TotpConfigDto -{ - [JsonPropertyName("secret_base32")] public string SecretBase32 { get; set; } = ""; - [JsonPropertyName("issuer")] public string? Issuer { get; set; } - [JsonPropertyName("account")] public string? Account { get; set; } - [JsonPropertyName("algorithm")] public string Algorithm { get; set; } = "SHA1"; - [JsonPropertyName("digits")] public int Digits { get; set; } = 6; - [JsonPropertyName("period")] public int Period { get; set; } = 30; - [JsonPropertyName("encoder")] public string Encoder { get; set; } = "totp"; -} - -public sealed class TotpCodeDto -{ - [JsonPropertyName("code")] public string Code { get; set; } = ""; - [JsonPropertyName("remaining")] public int Remaining { get; set; } - [JsonPropertyName("period")] public int Period { get; set; } = 30; - [JsonPropertyName("digits")] public int Digits { get; set; } = 6; - [JsonPropertyName("algorithm")] public string Algorithm { get; set; } = "SHA1"; - [JsonPropertyName("issuer")] public string? Issuer { get; set; } - [JsonPropertyName("account")] public string? Account { get; set; } -} - -public sealed class PasswordGenerateDto -{ - [JsonPropertyName("password")] public string Password { get; set; } = ""; - [JsonPropertyName("entropy_bits")] public double EntropyBits { get; set; } -} - -public sealed class SearchResponseDto -{ - [JsonPropertyName("matches")] public List Matches { get; set; } = new(); -} - -public sealed class SearchMatchDto -{ - [JsonPropertyName("entry")] public EntrySummaryDto Entry { get; set; } = new(); - [JsonPropertyName("matched_fields")] public List MatchedFields { get; set; } = new(); -} - -public sealed class CreateEntryResponse -{ - [JsonPropertyName("uuid")] public string Uuid { get; set; } = ""; -} - -public sealed class CreateGroupResponse -{ - [JsonPropertyName("uuid")] public string Uuid { get; set; } = ""; -} - -public sealed class ErrorDto -{ - [JsonPropertyName("code")] public string? Code { get; set; } - [JsonPropertyName("message")] public string? Message { get; set; } -} - -public sealed class SyncDecisionDto -{ - [JsonPropertyName("action")] public string Action { get; set; } = ""; - [JsonPropertyName("reason")] public string Reason { get; set; } = ""; - [JsonPropertyName("degraded")] public bool Degraded { get; set; } - [JsonPropertyName("retry_after_ms")] public long? RetryAfterMs { get; set; } -} - -public sealed class SyncConflictDto -{ - [JsonPropertyName("uuid")] public string Uuid { get; set; } = ""; - [JsonPropertyName("kind")] public string Kind { get; set; } = ""; - [JsonPropertyName("local_modified_unix")] public long? LocalModifiedUnix { get; set; } - [JsonPropertyName("remote_modified_unix")] public long? RemoteModifiedUnix { get; set; } - [JsonPropertyName("fields")] public List Fields { get; set; } = new(); -} - -public sealed record SyncMergeResult(byte[] Bytes, List Conflicts); diff --git a/apps/windows/Keepassity.Mock/MainWindow.xaml.cs b/apps/windows/Keepassity.Mock/MainWindow.xaml.cs deleted file mode 100644 index 07f2d46..0000000 --- a/apps/windows/Keepassity.Mock/MainWindow.xaml.cs +++ /dev/null @@ -1,6120 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-or-later -using Microsoft.UI.Windowing; -using Microsoft.UI.Xaml; -using Microsoft.UI.Xaml.Automation; -using Microsoft.UI.Xaml.Automation.Peers; -using Microsoft.UI.Xaml.Controls; -using Microsoft.UI.Xaml.Controls.Primitives; -using Microsoft.UI.Xaml.Input; -using Microsoft.UI.Xaml.Media; -using Microsoft.UI.Xaml.Media.Animation; -using Microsoft.UI.Xaml.Media.Imaging; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Net.NetworkInformation; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Security.Cryptography; -using System.Text.Json; -using Windows.ApplicationModel.DataTransfer; -using Windows.Graphics; -using Windows.Storage; -using Windows.Storage.Pickers; -using Windows.Storage.Streams; -using Windows.System; -using Windows.UI; - -namespace Keepassity.Mock; - -public sealed partial class MainWindow : Window -{ - public ObservableCollection Groups { get; } = new(); - public ObservableCollection Entries { get; } = new(); - - private readonly CoreClient _core = new(); - private readonly AppSettingsStore _settingsStore = new(); - private readonly SyncStateStore _syncStates = new(); - private readonly CredentialStore _credentials = new(); - private readonly SemaphoreSlim _syncGate = new(1, 1); - private readonly DispatcherTimer _totpTimer = new(); - private readonly DispatcherTimer _toastTimer = new(); - private readonly DispatcherTimer _autoLockTimer = new(); - private readonly DispatcherTimer _clipboardTimer = new(); - private readonly List _groupDtos = new(); - private readonly List _selectableGroups = new(); - private readonly Dictionary _groupNames = new(); - - private string? _dbPath; - private bool _webDavSource; - private string? _sourceWebDavUrl; - private string? _selectedGroupUuid; - private string? _recycleBinGroupUuid; - private string? _rootGroupUuid; - private EntryFullDto? _currentFull; - private EntryItem? _currentSummary; - private string? _currentTotpCode; - private string? _lastClipboardText; - private string? _masterPassword; - private TrayIcon? _trayIcon; - private bool _exitRequested; - private bool _trayHintShown; - private DateTimeOffset _lastActivity = DateTimeOffset.UtcNow; - private CancellationTokenSource? _searchCts; - private bool _passwordVisible; - private bool _busy; - private bool _suppressNav; - private int _showGeneration; - private string _entrySort = "title"; - private bool _onlyTotp; - private string _lastEntryFingerprint = string.Empty; - private Grid? _rightPanel; - private TextBlock? _rightPanelTitle; - private ContentControl? _rightPanelContent; - private StackPanel? _rightPanelActions; - private TaskCompletionSource? _rightPanelCompletion; - private bool _rightPanelOpen; - private Grid? _detailPanel; - private TextBlock? _detailPanelTitle; - private ContentControl? _detailPanelContent; - private StackPanel? _detailPanelActions; - private TaskCompletionSource? _detailPanelCompletion; - private bool _detailPanelOpen; - private readonly RecentDatabaseStore _recentDatabases = new(); - private readonly List _trayMenuDemoTimers = - new(); - private SessionLockMonitor? _sessionLockMonitor; - private SingleInstanceRelay? _singleInstanceRelay; - private Microsoft.UI.Dispatching.DispatcherQueueTimer? _networkReplayTimer; - private bool _sessionLockPending; - private TotpCodeDto? _totpDisplayedCode; - private string? _totpDisplayedUuid; - private TotpCodeDto? _totpPrefetchedCode; - private string? _totpPrefetchedUuid; - private long _totpWindowEndUnix = long.MaxValue; - private long _totpPrefetchTargetUnix = long.MinValue; - private bool _totpPrefetchInFlight; - private bool _announcePeerWarningLogged; - - private enum RightPanelResult - { - Primary, - Secondary, - Close, - } - - private AppSettings Settings => _settingsStore.Current; - - public MainWindow() - { - InitializeComponent(); - ApplyThemePreference(Settings.Theme); - Title = "keepassity"; - // The shell/taskbar icon is not inherited from the executable by WinUI 3; - // the window icon must be set explicitly (AppWindow.SetIcon needs a real - // .ico path for unpackaged apps). - ApplyWindowIcon(); - RestoreWindowBounds(); - ExtendsContentIntoTitleBar = true; - SetTitleBar(TitleBarDragArea); - ApplyTitleBarTheme(); - Root.ActualThemeChanged += (_, _) => - { - ApplyTitleBarTheme(); - _trayIcon?.ApplyTheme(Root.ActualTheme); - }; - SearchBox.Visibility = Visibility.Collapsed; - EntryList.ItemsSource = Entries; - ParseArguments(); - if (_dbPath is null && - !string.IsNullOrWhiteSpace(Settings.LastDatabasePath) && - File.Exists(Settings.LastDatabasePath)) - { - _dbPath = Settings.LastDatabasePath; - if (string.Equals(Settings.LastDatabaseKind, "webdav", - StringComparison.OrdinalIgnoreCase)) - { - _webDavSource = true; - _sourceWebDavUrl = Settings.LastWebDavUrl; - } - } - UpdateDatabasePath(); - - // Security: lock the vault on Windows session lock, logoff, session end - // and system suspend (see SessionLockMonitor). The network monitor - // replays pending WebDAV edits when connectivity comes back. - InitializeSessionLockMonitor(); - InitializeNetworkReplay(); - InitializeSingleInstanceRelay(); - - _totpTimer.Interval = TimeSpan.FromSeconds(1); - _totpTimer.Tick += async (_, _) => await UpdateTotpAsync(_showGeneration); - _toastTimer.Interval = TimeSpan.FromSeconds(4); - _toastTimer.Tick += (_, _) => - { - _toastTimer.Stop(); - Toast.IsOpen = false; - }; - _autoLockTimer.Interval = TimeSpan.FromSeconds(10); - _autoLockTimer.Tick += async (_, _) => await AutoLockTimer_Tick(); - _clipboardTimer.Interval = TimeSpan.FromSeconds(30); - _clipboardTimer.Tick += async (_, _) => await ClearClipboardTimer_Tick(); - Root.AddHandler(UIElement.PointerMovedEvent, - new PointerEventHandler((_, _) => TouchActivity()), true); - Root.AddHandler(UIElement.PointerPressedEvent, - new PointerEventHandler((_, _) => TouchActivity()), true); - Root.AddHandler(UIElement.KeyDownEvent, - new KeyEventHandler((_, _) => TouchActivity()), true); - Root.AddHandler(UIElement.KeyDownEvent, - new KeyEventHandler(RightPanel_KeyDown), true); - RegisterKeyboardAccelerators(); - Root.Loaded += Root_Loaded; - Closed += (_, _) => - { - SaveWindowBounds(); - _totpTimer.Stop(); - _sessionLockMonitor?.Dispose(); - _sessionLockMonitor = null; - _singleInstanceRelay?.Dispose(); - _singleInstanceRelay = null; - _networkReplayTimer?.Stop(); - NetworkChange.NetworkAvailabilityChanged -= OnNetworkAvailabilityChanged; - _trayIcon?.Dispose(); - _trayIcon = null; - _core.Dispose(); - }; - } - - private void InitializeTray() - { - if (TestHooks.HasSwitch("--no-tray")) - { - return; - } - try - { - _trayIcon = new TrayIcon("keepassity", Root.ActualTheme, AppAssets.AppIconPath, - ShowFromTray, LockFromTray, ExitFromTray); - _trayIcon.SetVaultState(_core.IsOpen, DisplayVaultName()); - if (_trayIcon.Element is UIElement trayElement && - !Root.Children.Contains(trayElement)) - { - Root.Children.Add(trayElement); - } - AppLog.Info($"tray icon available: {_trayIcon.Available}"); - AppWindow.Closing += AppWindow_Closing; - } - catch (Exception ex) - { - AppLog.Error("tray icon initialization failed", ex); - _trayIcon?.Dispose(); - _trayIcon = null; - } - } - - private void ShowFromTray() - { - AppWindow.Show(); - Activate(); - } - - private void LockFromTray() - { - if (!_core.IsOpen) - { - return; - } - if (_busy) - { - _trayIcon?.ShowInfo("keepassity", - "Busy saving or syncing; the vault was not locked. Try again in a moment."); - return; - } - // Lock in place: a tray lock must not raise the window (and with it the - // decrypted workspace) just to lock. If the window is visible it stays - // visible and switches to the unlock surface. - _ = LockVaultAsync(); - } - - private void ExitFromTray() - { - _exitRequested = true; - Close(); - } - - private void AppWindow_Closing(AppWindow sender, AppWindowClosingEventArgs args) - { - if (_exitRequested || _trayIcon is null || !_trayIcon.Available) - { - return; - } - args.Cancel = true; - AppWindow.Hide(); - if (!_trayHintShown) - { - _trayHintShown = true; - _trayIcon.ShowInfo("keepassity", - "Still running in the notification area. Use its menu to exit."); - } - } - - private void RestoreWindowBounds() - { - var fallback = new RectInt32(28, 40, 1650, 970); - if (Settings.WindowWidth is not int width || Settings.WindowHeight is not int height || - width < 800 || height < 600) - { - AppWindow.MoveAndResize(fallback); - return; - } - try - { - DisplayArea area = DisplayArea.GetFromWindowId(AppWindow.Id, - DisplayAreaFallback.Primary); - RectInt32 work = area.WorkArea; - width = Math.Min(width, work.Width); - height = Math.Min(height, work.Height); - int x = Settings.WindowX ?? work.X; - int y = Settings.WindowY ?? work.Y; - x = Math.Clamp(x, work.X, Math.Max(work.X, work.X + work.Width - 200)); - y = Math.Clamp(y, work.Y, Math.Max(work.Y, work.Y + work.Height - 100)); - AppWindow.MoveAndResize(new RectInt32(x, y, width, height)); - } - catch - { - AppWindow.MoveAndResize(fallback); - } - } - - private void SaveWindowBounds() - { - try - { - Settings.WindowX = AppWindow.Position.X; - Settings.WindowY = AppWindow.Position.Y; - Settings.WindowWidth = AppWindow.Size.Width; - Settings.WindowHeight = AppWindow.Size.Height; - _settingsStore.Save(); - } - catch - { - // Window bounds are a convenience; never block closing. - } - } - - private void ApplyThemePreference(string theme) - { - Root.RequestedTheme = theme switch - { - "Light" => ElementTheme.Light, - "Dark" => ElementTheme.Dark, - _ => ElementTheme.Default, - }; - ApplyWindowBackdrop(); - } - - private void TouchActivity() - { - _lastActivity = DateTimeOffset.UtcNow; - } - - private async Task AutoLockTimer_Tick() - { - if (!_core.IsOpen || _busy || !Settings.AutoLockEnabled) - { - return; - } - int minutes = Math.Clamp(Settings.AutoLockMinutes, 1, 240); - if (DateTimeOffset.UtcNow - _lastActivity >= TimeSpan.FromMinutes(minutes)) - { - await LockVaultAsync(); - } - } - - // ------------------------------------------------------- session lock - - private void InitializeSessionLockMonitor() - { - if (_sessionLockMonitor is not null) - { - return; - } - try - { - IntPtr window = WinRT.Interop.WindowNative.GetWindowHandle(this); - _sessionLockMonitor = SessionLockMonitor.TryInstall(window, OnSessionLockEvent); - if (_sessionLockMonitor is not null) - { - AppLog.Info("session lock monitor active"); - } - } - catch (Exception ex) - { - AppLog.Error("session lock monitor initialization failed", ex); - } - } - - /// Called on the UI thread by the window procedure subclass. - private void OnSessionLockEvent(string reason) - { - // Dispatch explicitly: LockVaultAsync awaits core work, and a lock must - // never run re-entrantly inside a window message handler. - DispatcherQueue.TryEnqueue(() => _ = LockForSessionEventAsync(reason)); - } - - private async Task LockForSessionEventAsync(string reason) - { - if (_sessionLockPending) - { - // Windows emits several messages for one lock/suspend transition; - // one in-flight lock request is enough. - return; - } - if (!_core.IsOpen) - { - AppLog.Info($"session event ignored ({reason}): vault already locked"); - return; - } - _sessionLockPending = true; - try - { - // A save/open may be in flight for a moment. Give it a short window to - // finish instead of racing it; never lock while a database write is - // still running. Edits are saved immediately in this app, so no save - // is needed here before locking. - for (int attempt = 0; attempt < 10 && _busy; attempt++) - { - await Task.Delay(200); - } - if (!_core.IsOpen) - { - AppLog.Info($"session event ({reason}): vault already locked"); - return; - } - if (_busy) - { - AppLog.Warn($"session event ({reason}): application busy; vault left " + - "unlocked (manual lock still available)"); - return; - } - AppLog.Info($"session event ({reason}): locking vault"); - await LockVaultAsync(); - } - catch (Exception ex) - { - AppLog.Error($"session event ({reason}): automatic lock failed", ex); - } - finally - { - _sessionLockPending = false; - } - } - - // --------------------------------------------------- network replay - - private void InitializeNetworkReplay() - { - try - { - _networkReplayTimer = DispatcherQueue.CreateTimer(); - _networkReplayTimer.Interval = TimeSpan.FromSeconds(2); - _networkReplayTimer.IsRepeating = false; - _networkReplayTimer.Tick += (_, _) => - { - _networkReplayTimer?.Stop(); - _ = ReplaySyncAfterNetworkReturnAsync(); - }; - NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged; - AppLog.Info("network change monitor active"); - } - catch (Exception ex) - { - AppLog.Error("network change monitor initialization failed", ex); - } - } - - private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e) - { - if (!e.IsAvailable || _exitRequested) - { - return; - } - // This event runs on a worker thread; only touch UI state through the - // dispatcher, and debounce the burst of events Windows raises while a - // connection settles. - DispatcherQueue.TryEnqueue(() => - { - if (_exitRequested || _networkReplayTimer is null) - { - return; - } - _networkReplayTimer.Stop(); - _networkReplayTimer.Start(); - }); - } - - private async Task ReplaySyncAfterNetworkReturnAsync() - { - if (!IsSyncConfigured) - { - return; - } - if (!_core.IsOpen || _dbPath is null) - { - AppLog.Info("network replay skipped: vault is locked"); - return; - } - if (_busy) - { - AppLog.Info("network replay skipped: application busy"); - return; - } - AppLog.Info("network replay: connectivity restored, syncing pending changes"); - await SyncAsync(); - } - - private async Task ClearClipboardTimer_Tick() - { - string? expected = _lastClipboardText; - _lastClipboardText = null; - _clipboardTimer.Stop(); - if (expected is null) - { - return; - } - try - { - DataPackageView content = Clipboard.GetContent(); - if (content.Contains(StandardDataFormats.Text) && - await content.GetTextAsync() == expected) - { - Clipboard.Clear(); - ShowToast("Clipboard cleared", InfoBarSeverity.Informational); - } - } - catch - { - // Clipboard can be locked by another process; leave it alone. - } - } - - private async void Root_Loaded(object sender, RoutedEventArgs e) - { - InitializeTray(); - ScheduleTrayMenuDemo(); - ScheduleSettingsDemo(); - // The HWND may not have existed during construction on some WinAppSDK - // versions; retry once the window is loaded. - if (_sessionLockMonitor is null) - { - InitializeSessionLockMonitor(); - } - if (Settings.StartMinimized && _trayIcon is { Available: true }) - { - AppWindow.Hide(); - } - string? devPassword = TestHooks.EnvironmentValue("KEEPASSITY_MOCK_PASSWORD"); - if (_dbPath is not null && !string.IsNullOrEmpty(devPassword)) - { - MasterPassword.Password = devPassword; - await UnlockAsync(); - } - } - - /// - /// Test hook for automated visual checks. KEEPASSITY_TRAY_MENU_AT="x,y" opens - /// the tray menu at that physical screen position shortly after startup. - /// KEEPASSITY_TRAY_MENU_SCHEDULE="1500,x,y;6000,x,y;7000,x,y" provides an - /// explicit list of delay/position entries (each call toggles the menu), which - /// lets a harness compare a first open with a repeated open in one process. - /// - private void ScheduleTrayMenuDemo() - { - if (_trayIcon is null) - { - return; - } - bool anchorToIcon = string.Equals( - TestHooks.EnvironmentValue("KEEPASSITY_TRAY_MENU_ANCHOR"), - "icon", StringComparison.OrdinalIgnoreCase); - string? schedule = TestHooks.EnvironmentValue("KEEPASSITY_TRAY_MENU_SCHEDULE"); - string? point = TestHooks.EnvironmentValue("KEEPASSITY_TRAY_MENU_AT"); - int pointX = 0; - int pointY = 0; - bool hasPoint = point is not null && TryParsePoint(point, out pointX, out pointY); - if (string.IsNullOrWhiteSpace(schedule)) - { - if (!hasPoint) - { - return; - } - schedule = "1500," + point; - } - foreach (string entry in schedule.Split(';', - StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) - { - string[] parts = entry.Split(','); - if (parts.Length != 3 || - !int.TryParse(parts[0].Trim(), out int delay) || - !int.TryParse(parts[1].Trim(), out int x) || - !int.TryParse(parts[2].Trim(), out int y)) - { - AppLog.Warn("tray menu test schedule entry must be delay,x,y"); - continue; - } - AddTrayMenuDemoTimer(TimeSpan.FromMilliseconds(Math.Max(100, delay)), - repeating: false, anchorToIcon, x, y); - } - // Repeating open/close cycle for interactive verification: keeps the menu - // appearing regularly so an external capture tool can catch it even when - // the reviewer misses the first window. - if (int.TryParse(TestHooks.EnvironmentValue("KEEPASSITY_TRAY_MENU_CYCLE_MS"), - out int cycle) && cycle >= 500 && hasPoint) - { - AddTrayMenuDemoTimer(TimeSpan.FromMilliseconds(cycle), - repeating: true, anchorToIcon, pointX, pointY); - } - } - - private static bool TryParsePoint(string specification, out int x, out int y) - { - x = 0; - y = 0; - string[] parts = specification.Split(','); - return parts.Length == 2 && - int.TryParse(parts[0].Trim(), out x) && - int.TryParse(parts[1].Trim(), out y); - } - - /// - /// Test hook for automated visual checks: KEEPASSITY_SETTINGS_DEMO_MS opens - /// the Settings panel once after that many milliseconds, which exercises the - /// About artwork loading path for an external capture tool. - /// - private void ScheduleSettingsDemo() - { - if (!int.TryParse(TestHooks.EnvironmentValue("KEEPASSITY_SETTINGS_DEMO_MS"), - out int delay) || delay < 500) - { - return; - } - var timer = DispatcherQueue.CreateTimer(); - timer.Interval = TimeSpan.FromMilliseconds(delay); - timer.IsRepeating = false; - timer.Tick += (_, _) => - { - timer.Stop(); - if (MainRoot.Visibility == Visibility.Visible && !_rightPanelOpen) - { - SettingsButton_Click(this, new RoutedEventArgs()); - } - }; - timer.Start(); - } - - private void AddTrayMenuDemoTimer(TimeSpan interval, bool repeating, bool anchorToIcon, - int x, int y) - { - var timer = DispatcherQueue.CreateTimer(); - timer.Interval = interval; - timer.IsRepeating = repeating; - timer.Tick += (_, _) => - { - if (anchorToIcon) - { - _trayIcon?.ShowMenuAtIconForTest(); - } - else - { - _trayIcon?.ShowMenuAt(x, y); - } - }; - _trayMenuDemoTimers.Add(timer); - timer.Start(); - } - - private void ParseArguments() - { - string[] args = Environment.GetCommandLineArgs(); - string? candidate = LaunchArguments.FindDatabasePath(args, File.Exists); - if (candidate is null) - { - return; - } - _dbPath = Path.GetFullPath(candidate); - // An explicit local file wins over a previously opened WebDAV - // source; drop that remote target so saves cannot overwrite it. - if (string.Equals(Settings.LastDatabaseKind, "webdav", - StringComparison.OrdinalIgnoreCase)) - { - Settings.WebDavUrl = null; - Settings.WebDavUsername = null; - } - Settings.LastDatabaseKind = "local"; - Settings.LastWebDavUrl = null; - Settings.LastWebDavUsername = null; - AppLog.Info("launch argument selected a local database"); - } - - private void UpdateDatabasePath() - { - RefreshRecentDatabaseList(); - bool hasDatabase = _dbPath is not null; - UnlockTitle.Text = hasDatabase ? "Unlock keepassity" : "keepassity"; - UnlockStartHint.Visibility = hasDatabase ? Visibility.Collapsed : Visibility.Visible; - DatabasePathText.Visibility = hasDatabase ? Visibility.Visible : Visibility.Collapsed; - UnlockFormSection.Visibility = hasDatabase ? Visibility.Visible : Visibility.Collapsed; - UnlockDivider.Visibility = hasDatabase ? Visibility.Visible : Visibility.Collapsed; - DatabaseActionsLabel.Visibility = hasDatabase ? Visibility.Visible : Visibility.Collapsed; - if (!hasDatabase) - { - UnlockError.IsOpen = false; - HideUnlockFailureActions(); - DatabasePathText.Text = "No database selected"; - ToolTipService.SetToolTip(DatabasePathText, - "Open a local .kdbx file or open from WebDAV"); - return; - } - if (_webDavSource && !string.IsNullOrWhiteSpace(_sourceWebDavUrl)) - { - DatabasePathText.Text = "WebDAV: " + _sourceWebDavUrl; - ToolTipService.SetToolTip(DatabasePathText, - _sourceWebDavUrl + Environment.NewLine + "Local working copy: " + _dbPath); - return; - } - DatabasePathText.Text = Path.GetFileName(_dbPath); - ToolTipService.SetToolTip(DatabasePathText, _dbPath); - } - - private string DisplayVaultName() - { - if (_webDavSource && !string.IsNullOrWhiteSpace(_sourceWebDavUrl)) - { - try - { - string name = Path.GetFileName(new Uri(_sourceWebDavUrl).AbsolutePath); - if (!string.IsNullOrWhiteSpace(name)) - { - return Path.GetFileNameWithoutExtension(Uri.UnescapeDataString(name)); - } - } - catch - { - // Fall back to the working-copy file name. - } - } - return _dbPath is null ? "Vault" : Path.GetFileNameWithoutExtension(_dbPath); - } - - // ------------------------------------------------------ window assets - - /// - /// Applies the branded application icon to the window (and thus the taskbar - /// and Alt+Tab switcher). WinUI 3 does not inherit the executable icon for a - /// window; the supported approach for unpackaged apps is - /// AppWindow.SetIcon with a fully qualified .ico path. - /// - private void ApplyWindowIcon() - { - string iconPath = AppAssets.AppIconPath; - if (File.Exists(iconPath)) - { - try - { - AppWindow.SetIcon(iconPath); - AppLog.Info("window icon applied from Assets/app.ico"); - return; - } - catch (Exception ex) - { - AppLog.Error("window icon could not be applied from Assets/app.ico", ex); - } - } - else - { - AppLog.Warn("window icon: Assets/app.ico is missing next to the executable"); - } - // Fallback: reuse the icon embedded in the executable by the - // ApplicationIcon project property so a missing Assets folder still - // produces a branded window icon. - try - { - string executable = Environment.ProcessPath ?? string.Empty; - if (string.IsNullOrEmpty(executable) || - ExtractIconEx(executable, 0, out IntPtr large, out IntPtr small, 1) == 0) - { - AppLog.Warn("window icon: no executable icon resource to fall back to"); - return; - } - IntPtr handle = large != IntPtr.Zero ? large : small; - if (handle != IntPtr.Zero) - { - AppWindow.SetIcon(Microsoft.UI.Win32Interop.GetIconIdFromIcon(handle)); - AppLog.Info("window icon applied from the embedded executable resource"); - } - } - catch (Exception ex) - { - AppLog.Error("window icon: embedded icon fallback failed", ex); - } - } - - [DllImport("shell32.dll", CharSet = CharSet.Unicode)] - private static extern uint ExtractIconEx(string file, int index, out IntPtr large, - out IntPtr small, uint count); - - // ------------------------------------------------------ keyboard input - - /// - /// Conventional desktop shortcuts. Accelerators live on the window content - /// root so they work regardless of which control has focus; the chosen keys - /// (Ctrl+F, Ctrl+L, Ctrl+N, Ctrl+S, F5) are not text-editing commands. - /// Escape is intentionally not an accelerator: Root_KeyDown already closes - /// the open right/detail panel, and flyouts close themselves natively. - /// - private void RegisterKeyboardAccelerators() - { - AddKeyboardAccelerator(VirtualKey.F, VirtualKeyModifiers.Control, - FocusSearchShortcut); - AddKeyboardAccelerator(VirtualKey.L, VirtualKeyModifiers.Control, - LockShortcut); - AddKeyboardAccelerator(VirtualKey.N, VirtualKeyModifiers.Control, - NewEntryShortcut); - AddKeyboardAccelerator(VirtualKey.S, VirtualKeyModifiers.Control, - SaveShortcut); - AddKeyboardAccelerator(VirtualKey.F5, VirtualKeyModifiers.None, - SyncShortcut); - } - - private void AddKeyboardAccelerator(VirtualKey key, VirtualKeyModifiers modifiers, - Action action) - { - var accelerator = new KeyboardAccelerator - { - Key = key, - Modifiers = modifiers, - }; - accelerator.Invoked += (_, args) => - { - args.Handled = true; - try - { - action(); - } - catch (Exception ex) - { - AppLog.Error($"keyboard shortcut {key} failed", ex); - } - }; - Root.KeyboardAccelerators.Add(accelerator); - } - - private void FocusSearchShortcut() - { - if (MainRoot.Visibility != Visibility.Visible || _busy) - { - return; - } - ClosePanels(); - SearchBox.Focus(FocusState.Programmatic); - } - - private void LockShortcut() - { - if (_core.IsOpen && !_busy) - { - _ = LockVaultAsync(); - } - } - - private void NewEntryShortcut() - { - // Never stack a second editor on top of an open panel or an in-flight - // save: the shortcut is only live when the workspace is idle. - if (!_core.IsOpen || _busy || _rightPanelOpen || _detailPanelOpen) - { - return; - } - NewEntryButton_Click(this, new RoutedEventArgs()); - } - - private void SyncShortcut() - { - if (!_core.IsOpen || _busy || !IsSyncConfigured) - { - return; - } - _ = SyncAsync(); - } - - private void SaveShortcut() - { - if (!_core.IsOpen) - { - return; - } - // Every edit path saves the database immediately, so Ctrl+S never needs - // to write the vault. Mapping it to "sync now" is the honest meaning of - // save for a synced database; without WebDAV it just reports the truth. - if (IsSyncConfigured) - { - ShowToast("Changes are saved automatically; syncing now…", - InfoBarSeverity.Informational); - _ = SyncAsync(); - } - else - { - ShowToast("Every change is saved automatically — nothing to save.", - InfoBarSeverity.Informational); - } - } - - // --------------------------------------------- single-instance relay - - private void InitializeSingleInstanceRelay() - { - _singleInstanceRelay = SingleInstanceRelay.TryStart(OnForwardedDatabaseRequest); - if (_singleInstanceRelay is null) - { - AppLog.Warn("open requests from a second launch will not be forwarded"); - } - } - - /// - /// Called on the UI thread from the relay window procedure when a second - /// launch hands over a .kdbx path. The actual lock/prefill work is deferred - /// so it never runs re-entrantly inside a window message (the sending - /// process is waiting for that message to be handled). - /// - private void OnForwardedDatabaseRequest(string databasePath) - { - DispatcherQueue.TryEnqueue(() => - { - try - { - AppWindow.Show(); - Activate(); - } - catch (Exception ex) - { - AppLog.Error("could not raise the window for a forwarded open request", ex); - } - _ = OpenExternalDatabaseAsync(databasePath, "another instance"); - }); - } - - // ------------------------------------------------------------ drag/drop - - private void Root_DragOver(object sender, DragEventArgs e) - { - // Only external file drops are handled at the window level. Drags that - // start inside the window (entry -> group) carry text, not StorageItems, - // and are left to the group drop targets. - if (!e.DataView.Contains(StandardDataFormats.StorageItems)) - { - return; - } - e.AcceptedOperation = DataPackageOperation.Copy; - e.DragUIOverride.Caption = "Open database"; - e.DragUIOverride.IsCaptionVisible = true; - e.DragUIOverride.IsGlyphVisible = false; - e.Handled = true; - } - - private async void Root_Drop(object sender, DragEventArgs e) - { - if (!e.DataView.Contains(StandardDataFormats.StorageItems)) - { - return; - } - e.Handled = true; - try - { - IReadOnlyList items = await e.DataView.GetStorageItemsAsync(); - StorageFile? database = items.OfType() - .FirstOrDefault(file => file.Name.EndsWith(".kdbx", - StringComparison.OrdinalIgnoreCase)); - if (database is null) - { - ShowToast("Only .kdbx database files can be opened this way.", - InfoBarSeverity.Warning); - return; - } - await OpenExternalDatabaseAsync(database.Path, "dropped file"); - } - catch (Exception ex) - { - AppLog.Error("dropped-file handling failed", ex); - ShowToast("The dropped file could not be read.", InfoBarSeverity.Error); - } - } - - /// - /// Opens a database selected outside the normal open dialog (dropped file or - /// a path forwarded by a second launch). Locks the current vault first, then - /// pre-fills the unlock page; same database and busy states are reported - /// instead of silently doing nothing. - /// - private async Task OpenExternalDatabaseAsync(string droppedPath, string origin) - { - if (_busy) - { - AppLog.Info($"open request ({origin}) ignored: application busy"); - ShowToast("Busy saving or syncing; try again in a moment.", - InfoBarSeverity.Informational); - return; - } - string fullPath; - try - { - fullPath = Path.GetFullPath(droppedPath); - } - catch - { - AppLog.Warn($"open request ({origin}) ignored: invalid path"); - ShowToast("The database path is not valid.", InfoBarSeverity.Error); - return; - } - if (!File.Exists(fullPath)) - { - AppLog.Warn($"open request ({origin}) ignored: file missing"); - ShowToast("The database file no longer exists.", InfoBarSeverity.Error); - return; - } - // MainRoot visibility is the reliable "vault is unlocked" signal here: - // CoreClient keeps its native handle after kp_lock, so _core.IsOpen stays - // true for a locked vault. - bool unlocked = MainRoot.Visibility == Visibility.Visible; - if (unlocked && string.Equals(_dbPath, fullPath, StringComparison.OrdinalIgnoreCase)) - { - AppLog.Info($"open request ({origin}) ignored: database already open"); - ShowToast("That database is already open.", InfoBarSeverity.Informational); - return; - } - if (unlocked) - { - // Opening another file means "open this instead": end the current - // session cleanly first (all edits are already saved). - await LockVaultAsync(); - if (MainRoot.Visibility == Visibility.Visible) - { - AppLog.Warn($"open request ({origin}) abandoned: the current vault " + - "could not be locked"); - return; - } - } - if (!string.Equals(_dbPath, fullPath, StringComparison.OrdinalIgnoreCase)) - { - _dbPath = fullPath; - _webDavSource = false; - _sourceWebDavUrl = null; - Settings.LastDatabaseKind = "local"; - Settings.LastWebDavUrl = null; - Settings.LastWebDavUsername = null; - // A different local file must not inherit another database's sync - // target, or a save could overwrite that remote database. - Settings.WebDavUrl = null; - Settings.WebDavUsername = null; - _settingsStore.Save(); - AppLog.Info($"open request ({origin}): unlock page prefilled"); - } - else - { - // Same database as the (locked) selection: just make sure the unlock - // surface is showing it. - AppLog.Info($"open request ({origin}): unlock page shown for the selected database"); - } - UpdateDatabasePath(); - UnlockError.Severity = InfoBarSeverity.Informational; - UnlockError.Title = "Database ready to unlock"; - UnlockError.Message = "Enter the master password to unlock this database."; - UnlockError.IsOpen = true; - HideUnlockFailureActions(); - MasterPassword.Focus(FocusState.Programmatic); - } - - // -------------------------------------------------------------- about - - private async Task ApplyAboutIconAsync(Image image) - { - if (await SetImageFromFileAsync(image, AppAssets.AppIconPreviewPath)) - { - image.Visibility = Visibility.Visible; - } - } - - /// - /// Loads a PNG next to the executable into an Image element. Unpackaged - /// WinUI 3 apps cannot rely on ms-appx URIs for files copied next to the - /// executable, so the bytes are streamed into a BitmapImage instead. - /// - private static async Task SetImageFromFileAsync(Image image, string path) - { - try - { - if (!File.Exists(path)) - { - AppLog.Warn("about icon asset is missing next to the executable"); - return false; - } - byte[] bytes = await File.ReadAllBytesAsync(path); - using var stream = new InMemoryRandomAccessStream(); - var writer = new DataWriter(stream); - try - { - writer.WriteBytes(bytes); - await writer.StoreAsync(); - await writer.FlushAsync(); - } - finally - { - writer.DetachStream(); - writer.Dispose(); - } - stream.Seek(0); - var bitmap = new BitmapImage(); - await bitmap.SetSourceAsync(stream); - image.Source = bitmap; - AppLog.Info("about icon loaded from Assets/app-icon-256.png"); - return true; - } - catch (Exception ex) - { - AppLog.Error("about icon could not be loaded", ex); - return false; - } - } - - private void ApplyWindowBackdrop() - { - Color pageColor = Root.RequestedTheme switch - { - ElementTheme.Light => Color.FromArgb(255, 243, 243, 243), - ElementTheme.Dark => Color.FromArgb(255, 32, 32, 32), - _ => Root.ActualTheme == ElementTheme.Light - ? Color.FromArgb(255, 243, 243, 243) - : Color.FromArgb(255, 32, 32, 32), - }; - try - { - if (Root.RequestedTheme == ElementTheme.Default) - { - // Mica follows the system theme; only use it when the app does too. - SystemBackdrop = new MicaBackdrop(); - Root.Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent); - } - else - { - SystemBackdrop = null; - Root.Background = new SolidColorBrush(pageColor); - } - } - catch - { - // Mica is unavailable on some Windows builds; keep the solid fallback. - SystemBackdrop = null; - Root.Background = new SolidColorBrush(pageColor); - } - } - - private void ApplyTitleBarTheme() - { - var titleBar = AppWindow.TitleBar; - bool light = Root.ActualTheme == ElementTheme.Light; - var transparent = Color.FromArgb(0, 0, 0, 0); - var foreground = light - ? Color.FromArgb(255, 28, 30, 36) - : Color.FromArgb(255, 245, 247, 250); - var inactive = light - ? Color.FromArgb(255, 110, 116, 128) - : Color.FromArgb(255, 170, 176, 188); - titleBar.ButtonForegroundColor = foreground; - titleBar.ButtonInactiveForegroundColor = inactive; - titleBar.ButtonBackgroundColor = transparent; - titleBar.ButtonInactiveBackgroundColor = transparent; - titleBar.ButtonHoverBackgroundColor = light - ? Color.FromArgb(255, 228, 231, 236) - : Color.FromArgb(255, 48, 52, 62); - titleBar.ButtonHoverForegroundColor = foreground; - titleBar.ButtonPressedBackgroundColor = light - ? Color.FromArgb(255, 212, 217, 224) - : Color.FromArgb(255, 64, 70, 84); - titleBar.ButtonPressedForegroundColor = foreground; - } - - /// The two workspace columns slide in independently. - private void AnimateWorkspace() - { - // Clear any previous whole-workspace animation state and animate the - // middle list and the detail column as separate surfaces instead. - WorkspacePanel.Opacity = 1; - WorkspacePanel.RenderTransform = null; - - var ease = new CubicEase { EasingMode = EasingMode.EaseOut }; - var duration = new Duration(TimeSpan.FromMilliseconds(280)); - var middleTransform = new TranslateTransform { X = 18 }; - var detailTransform = new TranslateTransform { X = 18 }; - EntryColumn.RenderTransform = middleTransform; - EntryColumn.Opacity = 0; - DetailPane.RenderTransform = detailTransform; - DetailPane.Opacity = 0; - - var storyboard = new Storyboard(); - void AddSlide(TranslateTransform transform) - { - var slide = new DoubleAnimation - { - To = 0, - Duration = duration, - EasingFunction = ease, - }; - Storyboard.SetTarget(slide, transform); - Storyboard.SetTargetProperty(slide, "X"); - storyboard.Children.Add(slide); - } - AddSlide(middleTransform); - var middleFade = new DoubleAnimation - { - To = 1, - Duration = duration, - EasingFunction = ease, - }; - Storyboard.SetTarget(middleFade, EntryColumn); - Storyboard.SetTargetProperty(middleFade, "Opacity"); - storyboard.Children.Add(middleFade); - - AddSlide(detailTransform); - var detailFade = new DoubleAnimation - { - To = 1, - Duration = duration, - EasingFunction = ease, - }; - Storyboard.SetTarget(detailFade, DetailPane); - Storyboard.SetTargetProperty(detailFade, "Opacity"); - storyboard.Children.Add(detailFade); - - storyboard.Begin(); - } - - /// Slide and fade a full-width or detail-column page into view. - private static void AnimatePanelIn(Grid panel, double offset = 28, int milliseconds = 220) - { - var transform = new TranslateTransform { X = offset }; - panel.RenderTransform = transform; - panel.Opacity = 0; - var ease = new CubicEase { EasingMode = EasingMode.EaseOut }; - var duration = new Duration(TimeSpan.FromMilliseconds(milliseconds)); - var storyboard = new Storyboard(); - var slide = new DoubleAnimation { To = 0, Duration = duration, EasingFunction = ease }; - Storyboard.SetTarget(slide, transform); - Storyboard.SetTargetProperty(slide, "X"); - var fade = new DoubleAnimation { To = 1, Duration = duration, EasingFunction = ease }; - Storyboard.SetTarget(fade, panel); - Storyboard.SetTargetProperty(fade, "Opacity"); - storyboard.Children.Add(slide); - storyboard.Children.Add(fade); - storyboard.Begin(); - } - - /// Fade a page out before the caller restores the content below it. - private static Task AnimatePanelOutAsync(Grid panel, double offset = 18, - int milliseconds = 140) - { - var completion = new TaskCompletionSource( - TaskCreationOptions.RunContinuationsAsynchronously); - var transform = panel.RenderTransform as TranslateTransform ?? new TranslateTransform(); - panel.RenderTransform = transform; - var ease = new CubicEase { EasingMode = EasingMode.EaseIn }; - var duration = new Duration(TimeSpan.FromMilliseconds(milliseconds)); - var storyboard = new Storyboard(); - var slide = new DoubleAnimation { To = offset, Duration = duration, EasingFunction = ease }; - Storyboard.SetTarget(slide, transform); - Storyboard.SetTargetProperty(slide, "X"); - var fade = new DoubleAnimation { To = 0, Duration = duration, EasingFunction = ease }; - Storyboard.SetTarget(fade, panel); - Storyboard.SetTargetProperty(fade, "Opacity"); - storyboard.Children.Add(slide); - storyboard.Children.Add(fade); - storyboard.Completed += (_, _) => - { - panel.Visibility = Visibility.Collapsed; - panel.Opacity = 1; - transform.X = 0; - completion.TrySetResult(); - }; - storyboard.Begin(); - return completion.Task; - } - - /// Small cross-fade when the selected entry details change. - private void AnimateDetailContent() - { - if (_detailPanelOpen) - { - return; - } - var transform = new TranslateTransform { X = 7 }; - DetailPane.RenderTransform = transform; - DetailPane.Opacity = 0.72; - var ease = new CubicEase { EasingMode = EasingMode.EaseOut }; - var duration = new Duration(TimeSpan.FromMilliseconds(170)); - var storyboard = new Storyboard(); - var slide = new DoubleAnimation { To = 0, Duration = duration, EasingFunction = ease }; - Storyboard.SetTarget(slide, transform); - Storyboard.SetTargetProperty(slide, "X"); - var fade = new DoubleAnimation { To = 1, Duration = duration, EasingFunction = ease }; - Storyboard.SetTarget(fade, DetailPane); - Storyboard.SetTargetProperty(fade, "Opacity"); - storyboard.Children.Add(slide); - storyboard.Children.Add(fade); - storyboard.Begin(); - } - - // ---------------------------------------------------------------- sync - - private bool IsSyncConfigured => - !string.IsNullOrWhiteSpace(Settings.WebDavUrl) && - !string.IsNullOrWhiteSpace(Settings.WebDavUsername); - - private void SetSyncStatus(string text) - { - SyncNavItem.Content = text; - Announce($"Sync status: {text}"); - } - - // ------------------------------------------------------ accessibility - - /// - /// Writes a short status message to the hidden live region and raises both a - /// live-region change and a UIA notification so screen readers announce - /// unlock, save, sync and lock results instead of the user having to find - /// the toast by hand. - /// - private void Announce(string message) - { - if (string.IsNullOrWhiteSpace(message)) - { - return; - } - try - { - StatusAnnouncement.Text = message; - AutomationPeer? peer = GetOrCreateAutomationPeer(StatusAnnouncement); - if (peer is null) - { - if (!_announcePeerWarningLogged) - { - _announcePeerWarningLogged = true; - AppLog.Warn("screen-reader announcement: no automation peer available"); - } - } - else - { - peer.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged); - peer.RaiseNotificationEvent(AutomationNotificationKind.ActionCompleted, - AutomationNotificationProcessing.ImportantMostRecent, message, - "keepassity.status"); - } - // Raising the same event on the now-visible toast gives screen readers - // a second, on-screen live-region source for the announcement. - if (Toast.IsOpen) - { - GetOrCreateAutomationPeer(Toast) - ?.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged); - } - } - catch (Exception ex) - { - AppLog.Warn($"screen-reader announcement failed: {ex.GetType().Name}"); - } - } - - private static AutomationPeer? GetOrCreateAutomationPeer(FrameworkElement element) - => FrameworkElementAutomationPeer.FromElement(element) ?? - FrameworkElementAutomationPeer.CreatePeerForElement(element); - - private static void SetButtonAutomation(Button button, string name, string? helpText = null, - string? automationId = null) - { - AutomationProperties.SetName(button, name); - if (!string.IsNullOrWhiteSpace(helpText)) - { - AutomationProperties.SetHelpText(button, helpText); - } - if (!string.IsNullOrWhiteSpace(automationId)) - { - AutomationProperties.SetAutomationId(button, automationId); - } - } - - private static string CertificateTrustKey(string url) - { - return Uri.TryCreate(url, UriKind.Absolute, out Uri? uri) - ? $"{uri.Host}:{uri.Port}" - : url; - } - - /// - /// Creates the WebDAV client, asking the user to confirm a self-signed server - /// certificate first (SY-04: explicit trust with fingerprint, never a global - /// validation bypass). Publicly trusted certificates need no prompt. - /// - private async Task CreateWebDavClientAsync(string url, string username, - string password) - { - if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? uri) || - uri.Scheme != Uri.UriSchemeHttps) - { - return new WebDavClient(url, username, password); - } - TlsCertificateInfo info; - try - { - info = await WebDavTls.ProbeAsync(uri.Host, uri.Port); - } - catch (WebDavException) - { - throw; - } - catch (Exception ex) - { - throw new WebDavException( - $"Could not check the TLS certificate of {uri.Host}:{uri.Port}: {ex.Message}"); - } - if (info.IsPubliclyTrusted) - { - return new WebDavClient(url, username, password); - } - string key = CertificateTrustKey(url); - if (Settings.TrustedCertificates.TryGetValue(key, out string? trusted) && - string.Equals(trusted, info.Sha256FingerprintHex, StringComparison.Ordinal)) - { - return new WebDavClient(url, username, password, trusted); - } - bool changed = Settings.TrustedCertificates.ContainsKey(key); - if (!await ConfirmWebDavCertificateAsync(info, changed)) - { - throw new WebDavException( - $"The certificate presented by {info.Endpoint} was not trusted, " + - "so the connection was cancelled."); - } - Settings.TrustedCertificates[key] = info.Sha256FingerprintHex; - _settingsStore.Save(); - AppLog.Info("trusted WebDAV certificate for " + key + - " (sha256 " + info.Sha256FingerprintHex + ")"); - return new WebDavClient(url, username, password, info.Sha256FingerprintHex); - } - - private async Task ConfirmWebDavCertificateAsync(TlsCertificateInfo info, bool changed) - { - var content = new StackPanel { Spacing = 8 }; - content.Children.Add(new TextBlock - { - Text = changed - ? "The server's certificate changed since it was trusted. Only continue " + - "if you changed it yourself or an administrator did." - : "Windows does not trust this server's certificate. That is normal for a " + - "self-signed certificate; only trust it if you installed the server or " + - "an administrator gave you this fingerprint.", - TextWrapping = TextWrapping.Wrap, - }); - void AddRow(string label, string value) - { - var row = new StackPanel { Spacing = 1 }; - row.Children.Add(new TextBlock - { - Text = label, - FontSize = 11, - Foreground = (Brush)Application.Current.Resources["TextFillColorTertiaryBrush"], - }); - row.Children.Add(new TextBlock - { - Text = value, - FontFamily = new FontFamily("Consolas"), - TextWrapping = TextWrapping.Wrap, - IsTextSelectionEnabled = true, - }); - content.Children.Add(row); - } - AddRow("Server", info.Endpoint); - AddRow("Subject", info.Subject); - AddRow("Issuer", info.Issuer); - AddRow("Expires", info.NotAfter.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")); - AddRow("SHA-256 fingerprint", info.Sha256FingerprintHex); - var dialog = new ContentDialog - { - Title = changed ? "Server certificate changed" : "Trust this server certificate?", - Content = content, - PrimaryButtonText = "Trust", - CloseButtonText = "Cancel", - DefaultButton = ContentDialogButton.Close, - XamlRoot = Root.XamlRoot, - }; - return await dialog.ShowAsync() == ContentDialogResult.Primary; - } - private async Task SyncAsync(bool startup = false) - { - if (!await _syncGate.WaitAsync(0)) - { - return; - } - try - { - if (!_core.IsOpen || _dbPath is null) - { - return; - } - if (!IsSyncConfigured) - { - SetSyncStatus("Local only"); - if (!startup) - { - ShowToast("Configure WebDAV in Settings first.", InfoBarSeverity.Informational); - } - return; - } - string url = Settings.WebDavUrl!.Trim(); - // A settings file written by an older build could still hold a plain - // http URL; never send Basic credentials over it (SY-03/SY-04 policy). - if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? syncUri) || - syncUri.Scheme != Uri.UriSchemeHttps) - { - SetSyncStatus("WebDAV needs https"); - if (!startup) - { - ShowToast("WebDAV sync requires an https:// URL: Basic " + - "authentication must use TLS.", InfoBarSeverity.Warning); - } - return; - } - string username = Settings.WebDavUsername!.Trim(); - string? password = _credentials.LoadPassword(url, username); - if (password is null) - { - SetSyncStatus("No credentials"); - if (!startup) - { - ShowToast("Set the WebDAV password in Settings.", InfoBarSeverity.Warning); - } - return; - } - - SetSyncStatus("Syncing…"); - SyncState state = _syncStates.Load(url, username, _dbPath); - if (!string.IsNullOrEmpty(state.Etag) || !string.IsNullOrEmpty(state.Sha256)) - { - await _core.SyncCommitAsync(state.Etag, state.Sha256); - } - using var dav = await CreateWebDavClientAsync(url, username, password); - WebDavFileInfo? metadata = await dav.GetMetadataAsync(); - if (metadata is null) - { - await UploadWithBackoffAsync(dav, state, url, username); - return; - } - - string remoteMeta = JsonSerializer.Serialize(new - { - etag = metadata.ETag, - size = metadata.Size, - modified_unix = metadata.ModifiedUnix, - reliability = metadata.ETag is null ? "degraded" : "full", - }); - SyncDecisionDto decision = await _core.SyncDecideAsync(remoteMeta, state.LocalDirty); - switch (decision.Action) - { - case "up_to_date": - state.Etag = metadata.ETag; - state.Size = metadata.Size; - state.RemoteModifiedUnix = metadata.ModifiedUnix; - state.LocalDirty = false; - state.LastSyncUnix = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); - await _core.SyncCommitAsync(state.Etag, state.Sha256); - _syncStates.Save(url, username, _dbPath, state); - SetSyncStatus(decision.Degraded ? "Synced (degraded)" : "Synced"); - break; - case "upload": - await UploadWithBackoffAsync(dav, state, url, username); - break; - case "download": - await DownloadRemoteAsync(dav, metadata, state, url, username); - break; - case "download_and_merge": - case "conflict": - await MergeRemoteAsync(dav, metadata, state, url, username); - break; - case "retry": - SetSyncStatus("Sync retry"); - break; - case "offline": - default: - SetSyncStatus("Offline"); - if (!startup) - { - ShowToast($"Sync skipped: {decision.Reason}", InfoBarSeverity.Warning); - } - break; - } - } - catch (WebDavException ex) - { - AppLog.Warn($"sync: {ex.Message}"); - SetSyncStatus(ex.Conflict ? "Conflict" : "Sync error"); - if (!startup) - { - ShowToast(ex.Message, InfoBarSeverity.Error); - } - } - catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException) - { - AppLog.Warn("webdav unreachable; working offline"); - SetSyncStatus("Offline"); - if (!startup) - { - ShowToast("WebDAV is unreachable; working offline.", InfoBarSeverity.Warning); - } - } - catch (Exception ex) - { - AppLog.Error("sync failed", ex); - SetSyncStatus("Sync error"); - if (!startup) - { - ShowToast($"Sync failed: {ex.Message}", InfoBarSeverity.Error); - } - } - finally - { - _syncGate.Release(); - } - } - - private async Task UploadLocalAsync(WebDavClient dav, SyncState state, string url, - string username) - { - byte[] bytes = await _core.SaveBytesAsync(); - await WriteLocalBytesAsync(_dbPath!, bytes); - // A 412 means the remote changed while we were preparing the upload; it - // is handled by UploadWithBackoffAsync, which retries with the core - // state machine's back-off schedule and merges after the last retry. - string? etag = await dav.UploadAsync(bytes, state.Etag); - string sha = Sha256Hex(bytes); - await _core.SyncCommitAsync(etag, sha); - state.Etag = etag; - state.Sha256 = sha; - state.Size = bytes.Length; - state.LocalDirty = false; - state.LastSyncUnix = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); - _syncStates.Save(url, username, _dbPath!, state); - SetSyncStatus("Synced"); - } - - /// - /// Uploads the current database, retrying a 412 (remote changed during the - /// upload) three times with the same 0.5 s / 1.5 s / 4 s back-off schedule as - /// the core sync state machine (SY-08). After the last retry the remote - /// change is resolved through the normal three-way merge/conflict path; the - /// remote is never overwritten silently. - /// - private async Task UploadWithBackoffAsync(WebDavClient dav, SyncState state, - string url, string username) - { - for (int attempt = 0; ; attempt++) - { - try - { - await UploadLocalAsync(dav, state, url, username); - return; - } - catch (WebDavException ex) when (ex.Conflict) - { - if (attempt >= 3) - { - AppLog.Warn("sync: PUT 412 after three back-off retries; merging"); - WebDavFileInfo? metadata = await dav.GetMetadataAsync(); - if (metadata is null) - { - throw; - } - SetSyncStatus("Resolving conflict"); - await MergeRemoteAsync(dav, metadata, state, url, username); - return; - } - int delayMs = attempt switch - { - 0 => 500, - 1 => 1500, - _ => 4000, - }; - SetSyncStatus($"Retrying sync in {delayMs} ms"); - AppLog.Warn($"sync: PUT 412, retry {attempt + 1}/3 after {delayMs} ms"); - await Task.Delay(delayMs); - } - } - } - - private async Task DownloadRemoteAsync(WebDavClient dav, WebDavFileInfo metadata, - SyncState state, string url, string username) - { - byte[] bytes = await dav.DownloadAsync(); - string sha = Sha256Hex(bytes); - bool contentChanged = true; - if (!string.IsNullOrEmpty(state.Sha256)) - { - contentChanged = !string.Equals(sha, state.Sha256, StringComparison.OrdinalIgnoreCase); - } - else if (_dbPath is not null && File.Exists(_dbPath)) - { - byte[] localBytes = await File.ReadAllBytesAsync(_dbPath); - contentChanged = !string.Equals(sha, Sha256Hex(localBytes), - StringComparison.OrdinalIgnoreCase); - } - if (contentChanged) - { - await WriteLocalBytesAsync(_dbPath!, bytes); - await ReopenFromLocalAsync(); - } - await _core.SyncCommitAsync(metadata.ETag, sha); - state.Etag = metadata.ETag; - state.Sha256 = sha; - state.Size = bytes.Length; - state.RemoteModifiedUnix = metadata.ModifiedUnix; - state.LocalDirty = false; - state.LastSyncUnix = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); - _syncStates.Save(url, username, _dbPath!, state); - SetSyncStatus("Synced"); - if (contentChanged) - { - ShowToast("Downloaded remote changes", InfoBarSeverity.Success); - } - } - - private async Task MergeRemoteAsync(WebDavClient dav, WebDavFileInfo metadata, - SyncState state, string url, string username) - { - byte[] remote = await dav.DownloadAsync(); - string? localCopy = CreateConflictCopy(); - string? remoteCopy = CreateRemoteConflictCopy(remote); - SyncMergeResult merged = await ProbeMergeAsync(remote); - if (merged.Conflicts.Count == 0) - { - await ApplyMergedAsync(dav, metadata, state, url, username, merged, - localCopy, remoteCopy, autoMerged: true); - return; - } - - ConflictChoice choice = await ShowConflictDialogAsync(localCopy, remoteCopy, - merged.Conflicts); - switch (choice) - { - case ConflictChoice.KeepLocal: - await KeepLocalConflictAsync(dav, metadata, state, url, username); - break; - case ConflictChoice.KeepRemote: - await KeepRemoteConflictAsync(dav, metadata, state, url, username, remote); - break; - case ConflictChoice.KeepBoth: - await ApplyMergedAsync(dav, metadata, state, url, username, merged, - localCopy, remoteCopy, autoMerged: false); - break; - default: - state.LocalDirty = true; - _syncStates.Save(url, username, _dbPath!, state); - SetSyncStatus("Conflict"); - ShowToast("Sync paused. Local and remote are unchanged; conflict copies were saved.", - InfoBarSeverity.Warning); - break; - } - } - - private enum ConflictChoice - { - Cancel, - KeepLocal, - KeepRemote, - KeepBoth, - } - - private async Task ShowConflictDialogAsync(string? localCopy, - string? remoteCopy, List conflicts) - { - var panel = new StackPanel { Spacing = 12 }; - panel.Children.Add(new TextBlock - { - Text = "Local and remote both changed. Conflict copies have been saved " + - "before asking what to do.", - TextWrapping = TextWrapping.Wrap, - FontSize = 13, - }); - panel.Children.Add(new TextBlock - { - Text = $"Local copy: {Path.GetFileName(localCopy)}\n" + - $"Remote copy: {Path.GetFileName(remoteCopy)}", - TextWrapping = TextWrapping.Wrap, - FontSize = 11, - Foreground = (Brush)Application.Current.Resources["TextFillColorSecondaryBrush"], - }); - if (conflicts.Count > 0) - { - var lines = conflicts.Take(6).Select(conflict => - { - string fields = conflict.Fields.Count == 0 - ? "entry changed on both sides" - : string.Join(", ", conflict.Fields); - return $"• {conflict.Kind}: {fields}"; - }); - panel.Children.Add(new TextBlock - { - Text = string.Join("\n", lines), - TextWrapping = TextWrapping.Wrap, - FontSize = 12, - }); - } - - ConflictChoice choice = ConflictChoice.Cancel; - var keepBoth = new Button - { - Content = "Keep both (recommended)", - HorizontalAlignment = HorizontalAlignment.Stretch, - Style = (Style)Application.Current.Resources["AccentButtonStyle"], - }; - var keepLocal = new Button - { - Content = "Keep local", - HorizontalAlignment = HorizontalAlignment.Stretch, - }; - var keepRemote = new Button - { - Content = "Keep remote", - HorizontalAlignment = HorizontalAlignment.Stretch, - }; - var cancel = new Button - { - Content = "Cancel and keep both files untouched", - HorizontalAlignment = HorizontalAlignment.Stretch, - }; - panel.Children.Add(keepBoth); - panel.Children.Add(keepLocal); - panel.Children.Add(keepRemote); - panel.Children.Add(cancel); - var dialog = new ContentDialog - { - Title = "Sync conflict", - Content = panel, - XamlRoot = Root.XamlRoot, - }; - keepBoth.Click += (_, _) => - { - choice = ConflictChoice.KeepBoth; - dialog.Hide(); - }; - keepLocal.Click += (_, _) => - { - choice = ConflictChoice.KeepLocal; - dialog.Hide(); - }; - keepRemote.Click += (_, _) => - { - choice = ConflictChoice.KeepRemote; - dialog.Hide(); - }; - cancel.Click += (_, _) => - { - choice = ConflictChoice.Cancel; - dialog.Hide(); - }; - dialog.Opened += (_, _) => keepBoth.Focus(FocusState.Programmatic); - await dialog.ShowAsync(); - return choice; - } - - private async Task ProbeMergeAsync(byte[] remote) - { - using var probe = new CoreClient(); - await probe.OpenAsync(_dbPath!, _masterPassword!); - try - { - return await probe.SyncMergeAsync(remote); - } - finally - { - await probe.LockAsync(); - } - } - - private async Task ApplyMergedAsync(WebDavClient dav, WebDavFileInfo metadata, - SyncState state, string url, string username, SyncMergeResult merged, - string? localCopy, string? remoteCopy, bool autoMerged) - { - await WriteLocalBytesAsync(_dbPath!, merged.Bytes); - await ReopenFromLocalAsync(); - string? etag; - try - { - etag = await dav.UploadAsync(merged.Bytes, metadata.ETag); - } - catch (WebDavException ex) when (ex.Conflict) - { - state.LocalDirty = true; - _syncStates.Save(url, username, _dbPath!, state); - SetSyncStatus("Conflict"); - ShowToast("Remote changed again; merged locally, will retry next sync.", - InfoBarSeverity.Warning); - return; - } - await CommitSyncedAsync(state, merged.Bytes, etag, metadata, url, username, - autoMerged ? "Synced" : "Merged"); - string copies = $"local: {Path.GetFileName(localCopy)}; remote: {Path.GetFileName(remoteCopy)}"; - ShowToast(autoMerged - ? $"Merged remote changes automatically ({copies})." - : $"Kept both versions; merged and uploaded ({copies}).", - InfoBarSeverity.Success); - } - - private async Task KeepLocalConflictAsync(WebDavClient dav, WebDavFileInfo metadata, - SyncState state, string url, string username) - { - byte[] localBytes = await File.ReadAllBytesAsync(_dbPath!); - string? etag; - try - { - etag = await dav.UploadAsync(localBytes, metadata.ETag); - } - catch (WebDavException ex) when (ex.Conflict) - { - state.LocalDirty = true; - _syncStates.Save(url, username, _dbPath!, state); - SetSyncStatus("Conflict"); - ShowToast("Remote changed again; local version kept, will retry next sync.", - InfoBarSeverity.Warning); - return; - } - await CommitSyncedAsync(state, localBytes, etag, metadata, url, username, "Synced"); - ShowToast("Kept local version; remote copy was saved.", InfoBarSeverity.Success); - } - - private async Task KeepRemoteConflictAsync(WebDavClient dav, WebDavFileInfo metadata, - SyncState state, string url, string username, byte[] remote) - { - await WriteLocalBytesAsync(_dbPath!, remote); - await ReopenFromLocalAsync(); - await CommitSyncedAsync(state, remote, metadata.ETag, metadata, url, username, - "Synced"); - ShowToast("Kept remote version; local copy was saved.", InfoBarSeverity.Success); - } - - private async Task CommitSyncedAsync(SyncState state, byte[] bytes, string? etag, - WebDavFileInfo metadata, string url, string username, string status) - { - string sha = Sha256Hex(bytes); - await _core.SyncCommitAsync(etag, sha); - state.Etag = etag; - state.Sha256 = sha; - state.Size = bytes.Length; - state.RemoteModifiedUnix = metadata.ModifiedUnix; - state.LocalDirty = false; - state.LastSyncUnix = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); - _syncStates.Save(url, username, _dbPath!, state); - SetSyncStatus(status); - } - - private async Task ReopenFromLocalAsync() - { - if (_dbPath is null || string.IsNullOrEmpty(_masterPassword)) - { - return; - } - await _core.OpenAsync(_dbPath, _masterPassword); - // Stay in the group the user is looking at; ReloadVaultAsync keeps the - // selected row and restores the wheel position. - await ReloadVaultAsync(_currentFull?.Uuid); - } - - private string? CreateConflictCopy() - { - if (_dbPath is null) - { - return null; - } - string directory = Path.GetDirectoryName(_dbPath)!; - string stem = Path.GetFileNameWithoutExtension(_dbPath); - string extension = Path.GetExtension(_dbPath); - string stamp = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"); - string path = Path.Combine(directory, $"{stem} (conflict {stamp}){extension}"); - int suffix = 1; - while (File.Exists(path)) - { - path = Path.Combine(directory, $"{stem} (conflict {stamp}-{suffix++}){extension}"); - } - File.Copy(_dbPath, path); - return path; - } - - private string? CreateRemoteConflictCopy(byte[] remote) - { - if (_dbPath is null) - { - return null; - } - string directory = Path.GetDirectoryName(_dbPath)!; - string stem = Path.GetFileNameWithoutExtension(_dbPath); - string extension = Path.GetExtension(_dbPath); - string stamp = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"); - string path = Path.Combine(directory, $"{stem} (remote conflict {stamp}){extension}"); - int suffix = 1; - while (File.Exists(path)) - { - path = Path.Combine(directory, - $"{stem} (remote conflict {stamp}-{suffix++}){extension}"); - } - File.WriteAllBytes(path, remote); - return path; - } - - private static string Sha256Hex(byte[] bytes) - => Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(); - - private async Task WriteLocalBytesAsync(string path, byte[] bytes) - { - string directory = Path.GetDirectoryName(Path.GetFullPath(path))!; - string temp = Path.Combine(directory, - $".{Path.GetFileName(path)}.keepassity-tmp-{Guid.NewGuid():N}"); - await File.WriteAllBytesAsync(temp, bytes); - if (File.Exists(path)) - { - BackupService.CreateBackup(path, Settings.BackupRetention, "sync"); - File.Replace(temp, path, path + ".keepassity-bak", true); - } - else - { - File.Move(temp, path); - } - } - - private void MarkLocalDirty() - { - if (_dbPath is null || !IsSyncConfigured) - { - return; - } - SyncState state = _syncStates.Load(Settings.WebDavUrl!.Trim(), - Settings.WebDavUsername!.Trim(), _dbPath); - state.LocalDirty = true; - _syncStates.Save(Settings.WebDavUrl!.Trim(), Settings.WebDavUsername!.Trim(), _dbPath, - state); - SetSyncStatus("Not synced"); - } - - private async Task ShowBackupsAsync() - { - if (_dbPath is null || _core.IsOpen == false) - { - return; - } - List backups = BackupService.ListBackups(_dbPath); - if (backups.Count == 0) - { - ShowToast("No backups yet. They are created before each save.", InfoBarSeverity.Informational); - return; - } - var choices = new ComboBox - { - Header = "Backup", - ItemsSource = backups, - SelectedIndex = 0, - HorizontalAlignment = HorizontalAlignment.Stretch, - }; - var content = new StackPanel { Spacing = 10 }; - content.Children.Add(new TextBlock - { - Text = $"Restoring backs up the current database first. Keeping {Settings.BackupRetention} copies.", - FontSize = 12, - TextWrapping = TextWrapping.Wrap, - Foreground = (Brush)Application.Current.Resources["TextFillColorSecondaryBrush"], - }); - content.Children.Add(choices); - if (await ShowDetailPanelAsync("Restore backup", content, "Restore", - primaryGlyph: "\uE777") != - RightPanelResult.Primary || - choices.SelectedItem is not BackupEntry selected) - { - return; - } - if (string.IsNullOrEmpty(_masterPassword)) - { - ShowToast("Unlock the vault before restoring a backup.", InfoBarSeverity.Warning); - return; - } - try - { - byte[] selectedBytes = await File.ReadAllBytesAsync(selected.Path); - using (var probe = new CoreClient()) - { - await probe.OpenAsync(selected.Path, _masterPassword); - await probe.LockAsync(); - } - await SaveAsync(silent: true, syncAfterSave: false); - BackupService.RestoreBytes(_dbPath, selectedBytes, Settings.BackupRetention); - await ReopenFromLocalAsync(); - MarkLocalDirty(); - ShowToast("Backup restored", InfoBarSeverity.Success); - if (IsSyncConfigured) - { - _ = SyncAsync(); - } - } - catch (Exception ex) - { - ShowToast($"Restore failed: {ex.Message}", InfoBarSeverity.Error); - } - } - - // ---------------------------------------------------------------- unlock - - private async void ChooseDatabaseButton_Click(object sender, RoutedEventArgs e) - { - var picker = new FileOpenPicker - { - SuggestedStartLocation = PickerLocationId.DocumentsLibrary, - }; - picker.FileTypeFilter.Add(".kdbx"); - WinRT.Interop.InitializeWithWindow.Initialize(picker, - WinRT.Interop.WindowNative.GetWindowHandle(this)); - var file = await picker.PickSingleFileAsync(); - if (file is null) - { - return; - } - if (string.Equals(Settings.LastDatabaseKind, "webdav", - StringComparison.OrdinalIgnoreCase)) - { - // Do not carry a previous WebDAV target over to an unrelated local - // file: saving it would overwrite that remote database. - Settings.WebDavUrl = null; - Settings.WebDavUsername = null; - } - else if (!string.Equals(Settings.LastDatabasePath, file.Path, - StringComparison.OrdinalIgnoreCase)) - { - // Switching to a different local database must not inherit the - // previous database's WebDAV target either. - Settings.WebDavUrl = null; - Settings.WebDavUsername = null; - } - _dbPath = file.Path; - _webDavSource = false; - _sourceWebDavUrl = null; - Settings.LastDatabaseKind = "local"; - Settings.LastWebDavUrl = null; - Settings.LastWebDavUsername = null; - _settingsStore.Save(); - UpdateDatabasePath(); - UnlockError.IsOpen = false; - HideUnlockFailureActions(); - } - - private async void OpenFromWebDavButton_Click(object sender, RoutedEventArgs e) - { - if (_busy) - { - return; - } - string initialUrl = Settings.LastWebDavUrl ?? Settings.WebDavUrl ?? string.Empty; - string initialUsername = Settings.LastWebDavUsername ?? Settings.WebDavUsername - ?? string.Empty; - var urlBox = new TextBox - { - Header = "WebDAV file URL", - Text = initialUrl, - PlaceholderText = "https://dav.jianguoyun.com/dav/keepassity/Keywords.kdbx", - }; - var userBox = new TextBox - { - Header = "WebDAV username", - Text = initialUsername, - }; - var passwordBox = new PasswordBox - { - Header = "WebDAV password", - PasswordRevealMode = PasswordRevealMode.Peek, - PlaceholderText = "Leave blank to use the stored password", - }; - var rememberBox = new CheckBox - { - Content = "Remember password with Windows DPAPI", - IsChecked = true, - }; - var errorText = new TextBlock - { - Foreground = (Brush)Application.Current.Resources["SystemFillColorCriticalBrush"], - TextWrapping = TextWrapping.Wrap, - Visibility = Visibility.Collapsed, - }; - // SY-09: server presets that fill in the URL shape of the common - // self-hosted WebDAV endpoints. - var preset = new ComboBox - { - Header = "Server preset", - HorizontalAlignment = HorizontalAlignment.Stretch, - }; - preset.Items.Add("Custom / paste a URL"); - preset.Items.Add("Nextcloud / ownCloud"); - preset.Items.Add("Synology WebDAV"); - preset.Items.Add("Jianguoyun (Nutstore)"); - preset.SelectedIndex = 0; - preset.SelectionChanged += (_, _) => - { - string? template = preset.SelectedIndex switch - { - 1 => "https://your-server/remote.php/dav/files/your-user/keepassity/Keywords.kdbx", - 2 => "https://your-server:5006/keepassity/Keywords.kdbx", - 3 => "https://dav.jianguoyun.com/dav/keepassity/Keywords.kdbx", - _ => null, - }; - if (template is null) - { - return; - } - urlBox.Text = template; - urlBox.SelectionStart = urlBox.Text.Length; - urlBox.Focus(FocusState.Programmatic); - }; - var content = new StackPanel { Spacing = 12 }; - content.Children.Add(preset); - content.Children.Add(urlBox); - content.Children.Add(userBox); - content.Children.Add(passwordBox); - content.Children.Add(rememberBox); - content.Children.Add(errorText); - content.Children.Add(new TextBlock - { - Text = "The .kdbx file is downloaded to an encrypted local working copy. " + - "Saves sync back to this URL; conflicts never overwrite silently. " + - "Nextcloud/ownCloud accounts with two-factor authentication need an " + - "app password, not the account password.", - FontSize = 11, - TextWrapping = TextWrapping.Wrap, - Foreground = (Brush)Application.Current.Resources["TextFillColorTertiaryBrush"], - }); - var dialog = new ContentDialog - { - Title = "Open from WebDAV", - Content = content, - PrimaryButtonText = "Open", - CloseButtonText = "Cancel", - DefaultButton = ContentDialogButton.Primary, - XamlRoot = Root.XamlRoot, - }; - dialog.PrimaryButtonClick += (_, args) => - { - string url = urlBox.Text.Trim(); - string username = userBox.Text.Trim(); - string? error = null; - if (!IsWebDavUrl(url)) - { - error = "Enter an https:// URL that points to the .kdbx file " + - "(Basic authentication requires TLS)."; - } - else if (username.Length == 0) - { - error = "Enter the WebDAV username."; - } - else if (passwordBox.Password.Length == 0 && - _credentials.LoadPassword(url, username) is null) - { - error = "Enter the WebDAV password (or use a URL whose credential is stored)."; - } - if (error is null) - { - return; - } - errorText.Text = error; - errorText.Visibility = Visibility.Visible; - args.Cancel = true; - }; - if (await dialog.ShowAsync() != ContentDialogResult.Primary) - { - return; - } - string remoteUrl = urlBox.Text.Trim(); - string remoteUsername = userBox.Text.Trim(); - string remotePassword = passwordBox.Password.Length > 0 - ? passwordBox.Password - : _credentials.LoadPassword(remoteUrl, remoteUsername) ?? string.Empty; - bool rememberPassword = rememberBox.IsChecked == true; - if (remotePassword.Length == 0) - { - ShowUnlockError("Cannot open database", "Enter the WebDAV password."); - return; - } - - _busy = true; - SetUnlockControlsEnabled(false); - UnlockError.IsOpen = false; - UnlockProgress.IsActive = true; - try - { - // Never overwrite a working copy that still holds unsynced edits: - // open it now and let the normal sync/merge path reconcile after unlock. - string pendingPath = RemoteDatabaseStore.PathFor(remoteUrl, remoteUsername); - SyncState pendingState = _syncStates.Load(remoteUrl, remoteUsername, pendingPath); - if (File.Exists(pendingPath) && pendingState.LocalDirty) - { - if (rememberPassword) - { - try - { - _credentials.SavePassword(remoteUrl, remoteUsername, remotePassword); - } - catch - { - // The pending-change path must not fail on credential storage. - } - } - ApplyWebDavSource(remoteUrl, remoteUsername, pendingPath); - UnlockError.Severity = InfoBarSeverity.Warning; - UnlockError.Title = "Unsynced local changes"; - UnlockError.Message = "The local working copy has changes that were not " + - "uploaded yet. Opening it; conflicts will be handled " + - "after unlock."; - UnlockError.IsOpen = true; - HideUnlockFailureActions(); - MasterPassword.Focus(FocusState.Programmatic); - return; - } - WebDavFileInfo? metadata; - byte[] bytes; - using (var dav = await CreateWebDavClientAsync(remoteUrl, remoteUsername, remotePassword)) - { - metadata = await dav.GetMetadataAsync(); - if (metadata is null) - { - throw new WebDavException( - "The remote database file was not found. Check the WebDAV file URL.", 404); - } - bytes = await dav.DownloadAsync(); - } - if (rememberPassword) - { - _credentials.SavePassword(remoteUrl, remoteUsername, remotePassword); - } - string workingPath = RemoteDatabaseStore.PathFor(remoteUrl, remoteUsername); - await WriteLocalBytesAsync(workingPath, bytes); - ApplyWebDavSource(remoteUrl, remoteUsername, workingPath); - SyncState state = _syncStates.Load(remoteUrl, remoteUsername, workingPath); - state.Etag = metadata.ETag; - state.Sha256 = Sha256Hex(bytes); - state.Size = bytes.Length; - state.RemoteModifiedUnix = metadata.ModifiedUnix; - state.LocalDirty = false; - state.LastSyncUnix = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); - _syncStates.Save(remoteUrl, remoteUsername, workingPath, state); - UnlockError.Severity = InfoBarSeverity.Success; - UnlockError.Title = "Downloaded from WebDAV"; - UnlockError.Message = - "Enter the master password to unlock. Saves will sync back to this file."; - UnlockError.IsOpen = true; - HideUnlockFailureActions(); - MasterPassword.Focus(FocusState.Programmatic); - } - catch (WebDavException ex) - { - ShowUnlockError("Cannot open database", ex.Message); - } - catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException) - { - string workingPath = RemoteDatabaseStore.PathFor(remoteUrl, remoteUsername); - if (File.Exists(workingPath)) - { - if (rememberPassword) - { - try - { - _credentials.SavePassword(remoteUrl, remoteUsername, remotePassword); - } - catch - { - // Offline fallback must not fail because of credential storage. - } - } - ApplyWebDavSource(remoteUrl, remoteUsername, workingPath); - UnlockError.Severity = InfoBarSeverity.Warning; - UnlockError.Title = "WebDAV unreachable"; - UnlockError.Message = "Opening the local working copy. " + - "Changes will sync when the network is back."; - UnlockError.IsOpen = true; - HideUnlockFailureActions(); - MasterPassword.Focus(FocusState.Programmatic); - } - else - { - ShowUnlockError("Cannot open database", ex.Message); - } - } - catch (Exception ex) - { - ShowUnlockError("Cannot open database", ex.Message); - } - finally - { - _busy = false; - SetUnlockControlsEnabled(true); - UnlockProgress.IsActive = false; - } - } - - /// - /// WebDAV URLs must use HTTPS: the password travels with Basic - /// authentication, which must never cross a plain-text connection. - /// - private static bool IsWebDavUrl(string url) - => Uri.TryCreate(url, UriKind.Absolute, out Uri? uri) && - uri.Scheme == Uri.UriSchemeHttps; - - private void ApplyWebDavSource(string url, string username, string workingPath) - { - _dbPath = workingPath; - _webDavSource = true; - _sourceWebDavUrl = url; - Settings.LastDatabaseKind = "webdav"; - Settings.LastWebDavUrl = url; - Settings.LastWebDavUsername = username; - Settings.LastDatabasePath = workingPath; - Settings.WebDavUrl = url; - Settings.WebDavUsername = username; - _settingsStore.Save(); - UpdateDatabasePath(); - RememberRecentDatabase(); - } - - private void ShowUnlockError(string title, string message) - { - UnlockError.Severity = InfoBarSeverity.Error; - UnlockError.Title = title; - UnlockError.Message = message; - UnlockError.IsOpen = true; - ShowUnlockFailureActions(); - Announce($"{title}: {message}"); - } - - private void SetUnlockControlsEnabled(bool enabled) - { - UnlockButton.IsEnabled = enabled; - ChooseDatabaseButton.IsEnabled = enabled; - OpenFromWebDavButton.IsEnabled = enabled; - NewDatabaseButton.IsEnabled = enabled; - } - - // ------------------------------------------------- recent databases - - private void RememberRecentDatabase() - { - if (_dbPath is null) - { - return; - } - if (_webDavSource && string.IsNullOrWhiteSpace(_sourceWebDavUrl)) - { - // A local working copy without a known remote URL is just a path. - _recentDatabases.Remember(_dbPath, "local"); - } - else - { - _recentDatabases.Remember(_dbPath, _webDavSource ? "webdav" : "local", - _webDavSource ? _sourceWebDavUrl : null, - _webDavSource ? Settings.WebDavUsername : null); - } - RefreshRecentDatabaseList(); - } - - private void RefreshRecentDatabaseList() - { - RecentDatabasesPanel.Children.Clear(); - IReadOnlyList entries = _recentDatabases.Entries; - foreach (RecentDatabaseEntry entry in entries) - { - var content = new StackPanel { Spacing = 2 }; - content.Children.Add(new TextBlock - { - Text = entry.DisplayName, - FontSize = 13, - TextTrimming = TextTrimming.CharacterEllipsis, - }); - string secondary = entry.Kind == "webdav" && - !string.IsNullOrWhiteSpace(entry.WebDavUrl) - ? "WebDAV · " + entry.WebDavUrl - : entry.Path; - content.Children.Add(new TextBlock - { - Text = secondary, - FontSize = 10, - MaxWidth = 320, - TextTrimming = TextTrimming.CharacterEllipsis, - Foreground = (Brush)Application.Current.Resources["TextFillColorTertiaryBrush"], - }); - var button = new Button - { - Content = content, - Style = (Style)Root.Resources["ToolbarButton"], - HorizontalAlignment = HorizontalAlignment.Stretch, - HorizontalContentAlignment = HorizontalAlignment.Left, - Padding = new Thickness(12, 8, 12, 8), - }; - AutomationProperties.SetName(button, $"Open recent database {entry.DisplayName}"); - AutomationProperties.SetHelpText(button, secondary); - button.Click += (_, _) => SelectRecentDatabase(entry); - var menu = new MenuFlyout(); - var remove = new MenuFlyoutItem { Text = "Remove from recent list" }; - remove.Click += (_, _) => - { - _recentDatabases.Remove(entry.Path); - RefreshRecentDatabaseList(); - }; - menu.Items.Add(remove); - button.ContextFlyout = menu; - RecentDatabasesPanel.Children.Add(button); - } - // The start page gets the list; when a database is already selected the - // unlock form takes its place. - RecentDatabasesSection.Visibility = _dbPath is null && entries.Count > 0 - ? Visibility.Visible - : Visibility.Collapsed; - } - - private void SelectRecentDatabase(RecentDatabaseEntry entry) - { - if (_busy) - { - return; - } - if (!File.Exists(entry.Path)) - { - UnlockError.Severity = InfoBarSeverity.Warning; - UnlockError.Title = "Database file not found"; - UnlockError.Message = "The database file is no longer at this path. It may have " + - "moved or be on a drive that is not connected. Use " + - "\"Open local file…\" to locate it again."; - UnlockError.IsOpen = true; - AppLog.Warn("recent database path is missing"); - return; - } - bool webDav = string.Equals(entry.Kind, "webdav", StringComparison.OrdinalIgnoreCase) && - !string.IsNullOrWhiteSpace(entry.WebDavUrl); - _dbPath = entry.Path; - _webDavSource = webDav; - _sourceWebDavUrl = webDav ? entry.WebDavUrl : null; - Settings.LastDatabasePath = entry.Path; - Settings.LastDatabaseKind = webDav ? "webdav" : "local"; - Settings.LastWebDavUrl = webDav ? entry.WebDavUrl : null; - Settings.LastWebDavUsername = webDav ? entry.WebDavUsername : null; - // Keep the sync target consistent with the selected database: a local - // file must never inherit another database's WebDAV target. - Settings.WebDavUrl = webDav ? entry.WebDavUrl : null; - Settings.WebDavUsername = webDav ? entry.WebDavUsername : null; - _settingsStore.Save(); - UnlockError.IsOpen = false; - HideUnlockFailureActions(); - UpdateDatabasePath(); - MasterPassword.Focus(FocusState.Programmatic); - } - - // ------------------------------------------------ unlock recovery - - private string CurrentBackupDirectory() - { - if (_dbPath is null) - { - return AppDataPaths.Root; - } - return BackupService.BackupDirectory(_dbPath); - } - - private void ShowUnlockFailureActions() - { - string backupDirectory = CurrentBackupDirectory(); - UnlockFailureHint.Text = "If the database will not open, export diagnostics (logs and " + - "settings only, no vault content or passwords) and keep them " + - "with the issue report. Timestamped backups are created before " + - "each save; the newest ones can be restored from the backup " + - "folder below."; - UnlockBackupPathText.Text = "Backups: " + backupDirectory; - ToolTipService.SetToolTip(UnlockBackupFolderButton, backupDirectory); - UnlockFailureActions.Visibility = Visibility.Visible; - } - - private void HideUnlockFailureActions() - { - UnlockFailureActions.Visibility = Visibility.Collapsed; - } - - private async void UnlockDiagnosticsButton_Click(object sender, RoutedEventArgs e) - { - try - { - string path = await DiagnosticsService.ExportAsync(Settings); - AppLog.Info("unlock page: diagnostics exported"); - ShowToast($"Diagnostics exported: {path}", InfoBarSeverity.Success); - await TryOpenFolderAsync(Path.GetDirectoryName(path)); - } - catch (Exception ex) - { - AppLog.Error("diagnostics export failed", ex); - ShowToast($"Diagnostics export failed: {ex.Message}", InfoBarSeverity.Error); - } - } - - private async void UnlockBackupFolderButton_Click(object sender, RoutedEventArgs e) - { - string directory = CurrentBackupDirectory(); - try - { - Directory.CreateDirectory(directory); - } - catch - { - // A read-only location still gets its path shown below. - } - if (!await TryOpenFolderAsync(directory)) - { - ShowToast($"Backup folder: {directory}", InfoBarSeverity.Informational); - } - } - - private static async Task TryOpenFolderAsync(string? path) - { - if (string.IsNullOrWhiteSpace(path)) - { - return false; - } - try - { - StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(path); - return await Launcher.LaunchFolderAsync(folder); - } - catch - { - return false; - } - } - - private async void NewDatabaseButton_Click(object sender, RoutedEventArgs e) - { - if (_busy) - { - return; - } - var nameBox = new TextBox - { - Header = "Database name", - Text = "keepassity", - }; - var targetChoices = new RadioButtons - { - Header = "Save to", - ItemsSource = new[] { "Local file", "WebDAV" }, - SelectedIndex = 0, - }; - var pathBox = new TextBox - { - Header = "Save as", - Text = DefaultNewDatabasePath(), - }; - var browse = new Button - { - Content = "Browse…", - VerticalAlignment = VerticalAlignment.Bottom, - Margin = new Thickness(8, 0, 0, 0), - }; - var pathRow = new Grid(); - pathRow.ColumnDefinitions.Add(new ColumnDefinition - { - Width = new GridLength(1, GridUnitType.Star), - }); - pathRow.ColumnDefinitions.Add(new ColumnDefinition - { - Width = GridLength.Auto, - }); - Grid.SetColumn(pathBox, 0); - Grid.SetColumn(browse, 1); - pathRow.Children.Add(pathBox); - pathRow.Children.Add(browse); - var localPanel = new StackPanel { Spacing = 12 }; - localPanel.Children.Add(pathRow); - var urlBox = new TextBox - { - Header = "WebDAV file URL", - Text = Settings.LastWebDavUrl ?? Settings.WebDavUrl ?? string.Empty, - PlaceholderText = "https://dav.jianguoyun.com/dav/keepassity/Keywords.kdbx", - }; - var userBox = new TextBox - { - Header = "WebDAV username", - Text = Settings.LastWebDavUsername ?? Settings.WebDavUsername ?? string.Empty, - }; - var remotePasswordBox = new PasswordBox - { - Header = "WebDAV password", - PasswordRevealMode = PasswordRevealMode.Peek, - PlaceholderText = "Leave blank to use the stored password", - }; - var rememberBox = new CheckBox - { - Content = "Remember password with Windows DPAPI", - IsChecked = true, - }; - var webdavPanel = new StackPanel { Spacing = 12, Visibility = Visibility.Collapsed }; - webdavPanel.Children.Add(urlBox); - webdavPanel.Children.Add(userBox); - webdavPanel.Children.Add(remotePasswordBox); - webdavPanel.Children.Add(rememberBox); - webdavPanel.Children.Add(new TextBlock - { - Text = "The new database is uploaded to this URL first. An existing remote " + - "file is never overwritten.", - FontSize = 11, - TextWrapping = TextWrapping.Wrap, - Foreground = (Brush)Application.Current.Resources["TextFillColorTertiaryBrush"], - }); - var passwordBox = new PasswordBox - { - Header = "Master password", - PasswordRevealMode = PasswordRevealMode.Peek, - }; - var confirmBox = new PasswordBox - { - Header = "Confirm master password", - PasswordRevealMode = PasswordRevealMode.Peek, - }; - var errorText = new TextBlock - { - Foreground = (Brush)Application.Current.Resources["SystemFillColorCriticalBrush"], - TextWrapping = TextWrapping.Wrap, - Visibility = Visibility.Collapsed, - }; - var content = new StackPanel { Spacing = 12 }; - content.Children.Add(nameBox); - content.Children.Add(targetChoices); - content.Children.Add(localPanel); - content.Children.Add(webdavPanel); - content.Children.Add(passwordBox); - content.Children.Add(confirmBox); - content.Children.Add(errorText); - content.Children.Add(new TextBlock - { - Text = "Creates an empty KDBX 4.0 database with a General group. " + - "The master password is not stored.", - FontSize = 11, - TextWrapping = TextWrapping.Wrap, - Foreground = (Brush)Application.Current.Resources["TextFillColorTertiaryBrush"], - }); - var dialog = new ContentDialog - { - Title = "New database", - Content = content, - PrimaryButtonText = "Create", - CloseButtonText = "Cancel", - DefaultButton = ContentDialogButton.Primary, - XamlRoot = Root.XamlRoot, - }; - targetChoices.SelectionChanged += (_, _) => - { - bool webdav = targetChoices.SelectedIndex == 1; - localPanel.Visibility = webdav ? Visibility.Collapsed : Visibility.Visible; - webdavPanel.Visibility = webdav ? Visibility.Visible : Visibility.Collapsed; - }; - browse.Click += async (_, _) => - { - var picker = new FolderPicker - { - SuggestedStartLocation = PickerLocationId.DocumentsLibrary, - }; - picker.FileTypeFilter.Add("*"); - WinRT.Interop.InitializeWithWindow.Initialize(picker, - WinRT.Interop.WindowNative.GetWindowHandle(this)); - StorageFolder? folder = await picker.PickSingleFolderAsync(); - if (folder is null) - { - return; - } - string stem = string.IsNullOrWhiteSpace(nameBox.Text) ? "keepassity" : nameBox.Text.Trim(); - pathBox.Text = Path.Combine(folder.Path, stem + ".kdbx"); - }; - dialog.PrimaryButtonClick += (_, args) => - { - string error = ValidateNewDatabaseNameAndPassword(nameBox.Text, - passwordBox.Password, confirmBox.Password); - if (error.Length == 0 && targetChoices.SelectedIndex == 0) - { - error = ValidateLocalDatabasePath(pathBox.Text); - } - if (error.Length == 0 && targetChoices.SelectedIndex == 1) - { - string url = urlBox.Text.Trim(); - string username = userBox.Text.Trim(); - if (!IsWebDavUrl(url)) - { - error = "Enter an absolute http(s) URL for the new database."; - } - else if (username.Length == 0) - { - error = "Enter the WebDAV username."; - } - else if (remotePasswordBox.Password.Length == 0 && - _credentials.LoadPassword(url, username) is null) - { - error = "Enter the WebDAV password (or use a URL whose credential is stored)."; - } - } - if (error.Length == 0) - { - return; - } - args.Cancel = true; - errorText.Text = error; - errorText.Visibility = Visibility.Visible; - }; - if (await dialog.ShowAsync() != ContentDialogResult.Primary) - { - return; - } - string databaseName = nameBox.Text.Trim(); - string password = passwordBox.Password; - bool useWebDav = targetChoices.SelectedIndex == 1; - string path = string.Empty; - if (ValidateNewDatabaseNameAndPassword(databaseName, password, - confirmBox.Password).Length > 0) - { - return; - } - if (!useWebDav) - { - try - { - path = Path.GetFullPath(pathBox.Text.Trim()); - } - catch - { - return; - } - if (ValidateLocalDatabasePath(path).Length > 0) - { - return; - } - } - string remoteUrl = urlBox.Text.Trim(); - string remoteUsername = userBox.Text.Trim(); - string remotePassword = remotePasswordBox.Password.Length > 0 - ? remotePasswordBox.Password - : _credentials.LoadPassword(remoteUrl, remoteUsername) ?? string.Empty; - bool rememberPassword = rememberBox.IsChecked == true; - - _busy = true; - UnlockError.IsOpen = false; - SetUnlockControlsEnabled(false); - UnlockProgress.IsActive = true; - try - { - byte[] bytes = await _core.CreateDatabaseAsync(databaseName, password); - if (useWebDav) - { - string workingPath = RemoteDatabaseStore.PathFor(remoteUrl, remoteUsername); - string? etag; - using (var dav = await CreateWebDavClientAsync(remoteUrl, remoteUsername, remotePassword)) - { - try - { - etag = await dav.UploadAsync(bytes, ifMatch: null); - } - catch (WebDavException ex) when (ex.Conflict) - { - throw new InvalidOperationException( - "The remote file already exists. Choose another URL or open it " + - "from WebDAV."); - } - } - if (rememberPassword) - { - _credentials.SavePassword(remoteUrl, remoteUsername, remotePassword); - } - await WriteLocalBytesAsync(workingPath, bytes); - ApplyWebDavSource(remoteUrl, remoteUsername, workingPath); - SyncState state = _syncStates.Load(remoteUrl, remoteUsername, workingPath); - state.Etag = etag; - state.Sha256 = Sha256Hex(bytes); - state.Size = bytes.Length; - state.RemoteModifiedUnix = null; - state.LocalDirty = false; - state.LastSyncUnix = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); - _syncStates.Save(remoteUrl, remoteUsername, workingPath, state); - await _core.OpenAsync(workingPath, password); - _masterPassword = password; - _selectedGroupUuid = null; - await ReloadVaultAsync(null); - UpdateDatabasePath(); - RememberRecentDatabase(); - ShowMain(); - MasterPassword.Password = string.Empty; - SetSyncStatus("Synced"); - ShowToast("Database created on WebDAV", InfoBarSeverity.Success); - } - else - { - string? directory = Path.GetDirectoryName(path); - if (!string.IsNullOrEmpty(directory)) - { - Directory.CreateDirectory(directory); - } - if (File.Exists(path)) - { - throw new InvalidOperationException( - "That file already exists. Choose another path."); - } - string temp = path + ".keepassity-new-tmp"; - await File.WriteAllBytesAsync(temp, bytes); - File.Move(temp, path); - _dbPath = path; - _webDavSource = false; - _sourceWebDavUrl = null; - await _core.OpenAsync(path, password); - _masterPassword = password; - _selectedGroupUuid = null; - Settings.LastDatabaseKind = "local"; - Settings.LastWebDavUrl = null; - Settings.LastWebDavUsername = null; - Settings.LastDatabasePath = path; - // A brand-new database starts without a sync target; carrying over - // the previous WebDAV URL could overwrite that remote file. - Settings.WebDavUrl = null; - Settings.WebDavUsername = null; - _settingsStore.Save(); - await ReloadVaultAsync(null); - UpdateDatabasePath(); - RememberRecentDatabase(); - ShowMain(); - MasterPassword.Password = string.Empty; - SetSyncStatus("Local only"); - ShowToast("Database created", InfoBarSeverity.Success); - } - } - catch (Exception ex) - { - UnlockError.Title = "Cannot create database"; - UnlockError.Severity = InfoBarSeverity.Error; - UnlockError.Message = ex.Message; - UnlockError.IsOpen = true; - } - finally - { - _busy = false; - SetUnlockControlsEnabled(true); - UnlockProgress.IsActive = false; - passwordBox.Password = string.Empty; - confirmBox.Password = string.Empty; - remotePasswordBox.Password = string.Empty; - } - } - - private static string ValidateNewDatabaseNameAndPassword(string name, string password, - string confirm) - { - if (string.IsNullOrWhiteSpace(name)) - { - return "Enter a database name."; - } - if (password.Length == 0) - { - return "Enter a master password."; - } - if (password != confirm) - { - return "The master passwords do not match."; - } - return string.Empty; - } - - private static string ValidateLocalDatabasePath(string path) - { - if (string.IsNullOrWhiteSpace(path)) - { - return "Choose where to save the database."; - } - if (!path.EndsWith(".kdbx", StringComparison.OrdinalIgnoreCase)) - { - return "The file name must end in .kdbx."; - } - return string.Empty; - } - private static string DefaultNewDatabasePath() - { - string directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); - if (string.IsNullOrEmpty(directory)) - { - directory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); - } - string path = Path.Combine(directory, "keepassity.kdbx"); - int suffix = 2; - while (File.Exists(path)) - { - path = Path.Combine(directory, $"keepassity-{suffix++}.kdbx"); - } - return path; - } - - private async void UnlockButton_Click(object sender, RoutedEventArgs e) - => await UnlockAsync(); - - private async void MasterPassword_KeyDown(object sender, KeyRoutedEventArgs e) - { - if (e.Key == VirtualKey.Enter) - { - await UnlockAsync(); - } - } - - private async Task UnlockAsync() - { - if (_busy) - { - return; - } - if (_dbPath is null) - { - UnlockError.Message = "Choose a .kdbx database first."; - UnlockError.IsOpen = true; - return; - } - if (MasterPassword.Password.Length == 0) - { - UnlockError.Message = "Enter the master password."; - UnlockError.IsOpen = true; - MasterPassword.Focus(FocusState.Programmatic); - return; - } - - _busy = true; - UnlockError.IsOpen = false; - SetUnlockControlsEnabled(false); - UnlockProgress.IsActive = true; - try - { - await _core.OpenAsync(_dbPath, MasterPassword.Password); - _masterPassword = MasterPassword.Password; - _selectedGroupUuid = null; - if (_dbPath is not null) - { - Settings.LastDatabasePath = _dbPath; - _settingsStore.Save(); - } - await ReloadVaultAsync(null); - UnlockError.IsOpen = false; - HideUnlockFailureActions(); - AppLog.Info("vault unlocked"); - Announce("Vault unlocked"); - _trayIcon?.SetVaultState(true, DisplayVaultName()); - RememberRecentDatabase(); - ShowMain(); - MasterPassword.Password = string.Empty; - _ = SyncAsync(startup: true); - } - catch (CoreException ex) - { - UnlockError.Title = ex.Code switch - { - "BadPassword" => "Wrong master password", - "CorruptDatabase" => "Database is damaged", - "UnsupportedFormat" => "Unsupported database", - _ => "Cannot open database", - }; - UnlockError.Message = ex.Message; - UnlockError.IsOpen = true; - ShowUnlockFailureActions(); - Announce($"Unlock failed: {ex.Message}"); - } - catch (Exception ex) - { - UnlockError.Title = "Cannot open database"; - UnlockError.Message = ex.Message; - UnlockError.IsOpen = true; - ShowUnlockFailureActions(); - Announce($"Unlock failed: {ex.Message}"); - } - finally - { - _busy = false; - SetUnlockControlsEnabled(true); - UnlockProgress.IsActive = false; - } - } - - private void ShowMain() - { - UnlockRoot.Visibility = Visibility.Collapsed; - MainRoot.Visibility = Visibility.Visible; - SearchBox.Visibility = Visibility.Visible; - HamburgerButton.Visibility = Visibility.Visible; - VaultNameText.Text = DisplayVaultName(); - _totpTimer.Start(); - _autoLockTimer.Start(); - TouchActivity(); - SetSyncStatus(IsSyncConfigured ? "Not synced" : "Local only"); - AnimateWorkspace(); - // Wait for the workspace to be laid out before taking focus, otherwise - // the first focusable title-bar control keeps the focus visual. - DispatcherQueue.TryEnqueue(() => EntryList.Focus(FocusState.Programmatic)); - } - - // ------------------------------------------------------------ vault data - - private async Task ReloadVaultAsync(string? selectEntryUuid, bool preserveScroll = true) - { - double entryScrollOffset = preserveScroll - ? FindDescendant(EntryList)?.VerticalOffset ?? 0 - : 0; - List groups = await _core.ListGroupsAsync(); - List allEntries = await _core.ListEntriesAsync(); - - _groupDtos.Clear(); - _selectableGroups.Clear(); - _groupNames.Clear(); - _recycleBinGroupUuid = null; - _rootGroupUuid = groups.FirstOrDefault(group => group.ParentUuid is null)?.Uuid; - foreach (GroupDto group in groups) - { - _groupDtos.Add(group); - string name = string.IsNullOrWhiteSpace(group.Name) ? "Vault" : group.Name; - _groupNames[group.Uuid] = name; - if (_recycleBinGroupUuid is null && IsRecycleBinGroup(name)) - { - _recycleBinGroupUuid = group.Uuid; - } - if (group.Uuid != _rootGroupUuid && !string.IsNullOrWhiteSpace(group.Name)) - { - _selectableGroups.Add(group); - } - } - if (_selectableGroups.Count == 0 && _groupDtos.Count > 0) - { - _selectableGroups.AddRange(_groupDtos); - } - - Groups.Clear(); - int activeEntryCount = allEntries.Count(entry => - _recycleBinGroupUuid is null || entry.GroupUuid != _recycleBinGroupUuid); - Groups.Add(new GroupItem(null, "All entries", activeEntryCount, "\uE8FD")); - GroupItem? recycleBin = null; - GroupItem? templates = null; - var otherGroups = new List(); - foreach (GroupDto group in _groupDtos) - { - if (group.Uuid == _rootGroupUuid || string.IsNullOrWhiteSpace(group.Name)) - { - continue; - } - int count = allEntries.Count(entry => entry.GroupUuid == group.Uuid); - var item = new GroupItem(group.Uuid, group.Name, count, "\uE8B7"); - if (IsRecycleBinGroup(group.Name) && recycleBin is null) - { - recycleBin = item; - } - else if (IsTemplatesGroup(group.Name) && templates is null) - { - templates = item; - } - else - { - otherGroups.Add(item); - } - } - // Normal groups keep the vault order; template groups are pinned above - // the recycle bin, which is always the last navigation item. - foreach (GroupItem item in otherGroups) - { - Groups.Add(item); - } - if (templates is not null) - { - Groups.Add(templates); - } - if (recycleBin is not null) - { - Groups.Add(recycleBin); - } - PopulateNavigation(_selectedGroupUuid); - - string title = _selectedGroupUuid is null - ? "All entries" - : _groupNames.GetValueOrDefault(_selectedGroupUuid, "Entries"); - List visible = _selectedGroupUuid is null - ? allEntries - .Where(entry => _recycleBinGroupUuid is null || - entry.GroupUuid != _recycleBinGroupUuid) - .ToList() - : allEntries.Where(entry => entry.GroupUuid == _selectedGroupUuid).ToList(); - string? previousSelection = (EntryList.SelectedItem as EntryItem)?.Uuid; - PopulateEntries(visible, title, selectEntryUuid ?? previousSelection); - - // Restoring the wheel position after a reload is what keeps a merge or a - // metadata change from jumping the list back to the top. - if (preserveScroll && entryScrollOffset > 0) - { - RestoreEntryScrollOffset(entryScrollOffset); - } - } - - private static T? FindDescendant(DependencyObject? root) where T : DependencyObject - { - if (root is null) - { - return null; - } - int count = VisualTreeHelper.GetChildrenCount(root); - for (int index = 0; index < count; index++) - { - DependencyObject child = VisualTreeHelper.GetChild(root, index); - if (child is T match) - { - return match; - } - T? nested = FindDescendant(child); - if (nested is not null) - { - return nested; - } - } - return null; - } - - private void PopulateNavigation(string? selectedUuid) - { - _suppressNav = true; - NavView.MenuItems.Clear(); - NavigationViewItem? selectedItem = null; - NavigationViewItem? first = null; - foreach (GroupItem group in Groups) - { - var item = new NavigationViewItem - { - Content = group.Name, - Tag = group.Uuid ?? "all", - Icon = new FontIcon { Glyph = group.Glyph }, - ContextFlyout = BuildGroupContextMenu(group), - }; - if (group.Uuid is not null) - { - item.AllowDrop = true; - item.DragOver += GroupNavItem_DragOver; - item.DragLeave += GroupNavItem_DragLeave; - item.Drop += GroupNavItem_Drop; - } - if (group.CountValue > 0 && - !IsRecycleBinGroup(group.Name) && - !IsTemplatesGroup(group.Name)) - { - item.InfoBadge = new InfoBadge { Value = group.CountValue }; - } - NavView.MenuItems.Add(item); - first ??= item; - if ((selectedUuid is null && group.Uuid is null) || - (selectedUuid is not null && group.Uuid == selectedUuid)) - { - selectedItem = item; - } - } - NavView.SelectedItem = selectedItem ?? first; - _suppressNav = false; - } - - private void SelectNavItem(NavigationViewItem? item) - { - bool previousSuppress = _suppressNav; - _suppressNav = true; - NavView.SelectedItem = item; - _suppressNav = previousSuppress; - } - - private void SetSettingsHighlight(bool highlighted) - { - if (highlighted) - { - SettingsNavItem.Background = - (Brush)Application.Current.Resources["SubtleFillColorSecondaryBrush"]; - } - else - { - SettingsNavItem.ClearValue(Control.BackgroundProperty); - } - } - - private void RestoreGroupNavSelection() - { - string tag = _selectedGroupUuid ?? "all"; - NavigationViewItem? item = NavView.MenuItems - .OfType() - .FirstOrDefault(candidate => (candidate.Tag as string) == tag); - item ??= NavView.MenuItems.OfType().FirstOrDefault(); - if (item is not null) - { - SelectNavItem(item); - } - } - - private static bool IsRecycleBinGroup(string name) - { - string value = name.Trim(); - return value.Equals("回收站", StringComparison.OrdinalIgnoreCase) || - value.Equals("Recycle Bin", StringComparison.OrdinalIgnoreCase) || - value.Equals("RecycleBin", StringComparison.OrdinalIgnoreCase); - } - - private static bool IsTemplatesGroup(string name) - { - string value = name.Trim(); - return value.Equals("模板", StringComparison.OrdinalIgnoreCase) || - value.Equals("Templates", StringComparison.OrdinalIgnoreCase) || - value.Equals("Template", StringComparison.OrdinalIgnoreCase); - } - - private MenuFlyout BuildGroupContextMenu(GroupItem group) - { - var flyout = new MenuFlyout(); - void Add(string text, string glyph, Func action, - bool enabled = true, bool danger = false) - { - var item = new MenuFlyoutItem - { - Text = text, - Icon = new FontIcon { Glyph = glyph, FontSize = 12 }, - IsEnabled = enabled, - }; - if (danger) - { - item.Foreground = - (Brush)Application.Current.Resources["SystemFillColorCriticalBrush"]; - } - item.Click += async (_, _) => - { - try - { - await action(); - } - catch (Exception ex) - { - ShowToast(ex.Message, InfoBarSeverity.Error); - } - }; - flyout.Items.Add(item); - } - - Add("New group…", "\uE710", CreateGroupPromptAsync, - enabled: !string.IsNullOrEmpty(_rootGroupUuid)); - if (group.Uuid is null) - { - Add("New entry", "\uE710", () => - { - NewEntryButton_Click(this, new RoutedEventArgs()); - return Task.CompletedTask; - }); - return flyout; - } - - bool recycleBin = IsRecycleBinGroup(group.Name); - if (!recycleBin) - { - Add("New entry here", "\uE710", - () => NewEntryInGroupAsync(group.Uuid!)); - } - if (recycleBin) - { - return flyout; - } - - flyout.Items.Add(new MenuFlyoutSeparator()); - Add("Rename group…", "\uE70F", () => RenameGroupPromptAsync(group)); - Add("Delete group", "\uE74D", () => DeleteGroupAsync(group), danger: true); - return flyout; - } - - private async Task CreateGroupPromptAsync() - { - if (string.IsNullOrEmpty(_rootGroupUuid)) - { - return; - } - string? name = await PromptForNameAsync("New group", "Group name", string.Empty); - if (string.IsNullOrWhiteSpace(name)) - { - return; - } - string uuid = await _core.CreateGroupAsync(_rootGroupUuid, name); - await SaveAsync(); - _selectedGroupUuid = uuid; - await ReloadVaultAsync(null, preserveScroll: false); - ShowToast($"Group \"{name}\" created", InfoBarSeverity.Success); - } - - private async Task RenameGroupPromptAsync(GroupItem group) - { - if (group.Uuid is null) - { - return; - } - string? name = await PromptForNameAsync("Rename group", "Group name", group.Name); - if (string.IsNullOrWhiteSpace(name) || - string.Equals(name, group.Name, StringComparison.Ordinal)) - { - return; - } - await _core.RenameGroupAsync(group.Uuid, name); - await SaveAsync(); - await ReloadVaultAsync(_selectedGroupUuid); - ShowToast("Group renamed", InfoBarSeverity.Success); - } - - private async Task DeleteGroupAsync(GroupItem group) - { - if (group.Uuid is null) - { - return; - } - bool hasEntries = group.CountValue > 0; - var dialog = new ContentDialog - { - Title = hasEntries ? "Delete group and contents?" : "Delete group?", - Content = hasEntries - ? $"\"{group.Name}\" and everything inside it will be permanently deleted. This cannot be undone." - : $"The empty group \"{group.Name}\" will be removed.", - PrimaryButtonText = "Delete", - CloseButtonText = "Cancel", - DefaultButton = ContentDialogButton.Close, - XamlRoot = Root.XamlRoot, - }; - if (await dialog.ShowAsync() != ContentDialogResult.Primary) - { - return; - } - await _core.DeleteGroupAsync(group.Uuid); - if (_selectedGroupUuid == group.Uuid) - { - _selectedGroupUuid = null; - } - await SaveAsync(); - await ReloadVaultAsync(null, preserveScroll: false); - ShowToast("Group deleted", InfoBarSeverity.Success); - } - - private async Task PromptForNameAsync(string title, string label, - string initial) - { - var box = new TextBox - { - Header = label, - Text = initial, - }; - var dialog = new ContentDialog - { - Title = title, - Content = box, - PrimaryButtonText = initial.Length == 0 ? "Create" : "Rename", - CloseButtonText = "Cancel", - DefaultButton = ContentDialogButton.Primary, - XamlRoot = Root.XamlRoot, - }; - return await dialog.ShowAsync() == ContentDialogResult.Primary - ? box.Text.Trim() - : null; - } - - private async Task NewEntryInGroupAsync(string groupUuid) - { - _selectedGroupUuid = groupUuid; - NavigationViewItem? item = NavView.MenuItems - .OfType() - .FirstOrDefault(candidate => (candidate.Tag as string) == groupUuid); - if (item is not null) - { - NavView.SelectedItem = item; - } - NewEntryButton_Click(this, new RoutedEventArgs()); - await Task.CompletedTask; - } - - private void GroupNavItem_DragOver(object sender, DragEventArgs e) - { - if (sender is not NavigationViewItem item || - item.Tag is not string groupUuid || - groupUuid == "all" || - !e.DataView.Contains(StandardDataFormats.Text)) - { - return; - } - item.Background = - (Brush)Application.Current.Resources["AccentFillColorSecondaryBrush"]; - item.BorderBrush = - (Brush)Application.Current.Resources["AccentFillColorDefaultBrush"]; - item.BorderThickness = new Thickness(1); - e.AcceptedOperation = DataPackageOperation.Move; - e.DragUIOverride.Caption = $"Move to {item.Content}"; - e.DragUIOverride.IsCaptionVisible = true; - e.DragUIOverride.IsGlyphVisible = false; - e.Handled = true; - } - - private void GroupNavItem_DragLeave(object sender, DragEventArgs e) - { - if (sender is NavigationViewItem item) - { - ClearGroupDragHighlight(item); - } - } - - private static void ClearGroupDragHighlight(NavigationViewItem item) - { - item.ClearValue(Control.BackgroundProperty); - item.ClearValue(Control.BorderBrushProperty); - item.ClearValue(Control.BorderThicknessProperty); - } - - private async void GroupNavItem_Drop(object sender, DragEventArgs e) - { - if (sender is not NavigationViewItem item || - item.Tag is not string targetGroupUuid || - targetGroupUuid == "all" || - !e.DataView.Contains(StandardDataFormats.Text)) - { - return; - } - e.Handled = true; - ClearGroupDragHighlight(item); - string entryUuid = (await e.DataView.GetTextAsync()).Trim(); - if (entryUuid.Length == 0) - { - return; - } - EntryItem? movedItem = Entries.FirstOrDefault(entry => entry.Uuid == entryUuid); - string? sourceGroupUuid = movedItem?.GroupUuid; - double scrollOffset = CaptureEntryScrollOffset(); - try - { - await _core.MoveEntryAsync(entryUuid, targetGroupUuid); - await SaveAsync(); - // Update only the affected row(s); a full reload would reset the - // scroll position for a move that usually does not change the view. - ApplyEntryMovedLocally(entryUuid, sourceGroupUuid, targetGroupUuid, - item.Content as string ?? _groupNames.GetValueOrDefault(targetGroupUuid, "the group")); - RestoreEntryScrollOffset(scrollOffset); - ShowToast($"Moved to {item.Content}", InfoBarSeverity.Success); - } - catch (Exception ex) - { - ShowToast(ex.Message, InfoBarSeverity.Error); - } - } - - private static ScrollViewer? FindEntryScrollViewer(DependencyObject root) - { - int count = VisualTreeHelper.GetChildrenCount(root); - for (int index = 0; index < count; index++) - { - DependencyObject child = VisualTreeHelper.GetChild(root, index); - if (child is ScrollViewer scrollViewer) - { - return scrollViewer; - } - ScrollViewer? nested = FindEntryScrollViewer(child); - if (nested is not null) - { - return nested; - } - } - return null; - } - - private double CaptureEntryScrollOffset() - => FindEntryScrollViewer(EntryList)?.VerticalOffset ?? 0; - - private void RestoreEntryScrollOffset(double offset) - { - if (offset <= 0) - { - return; - } - void Apply() - { - ScrollViewer? scrollViewer = FindEntryScrollViewer(EntryList); - if (scrollViewer is null) - { - return; - } - if (Math.Abs(scrollViewer.VerticalOffset - offset) > 0.5) - { - scrollViewer.ChangeView(null, offset, null, true); - } - } - // Two deferred passes: the first runs after the rebuild, the second after - // the ListView's own selection/layout work, which may scroll a selected - // row into view and would otherwise win over a single restore. - DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Low, () => - { - EntryList.UpdateLayout(); - Apply(); - DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Low, Apply); - }); - } - - /// - /// Rebuilds the middle column only when its visible content actually changed. - /// Merges and moves should not make the list jump back to the top, so an - /// identical entry list keeps the existing rows (and their scroll offset); - /// when a rebuild is needed the previous selection is kept and the caller - /// restores the wheel position afterwards. - /// - /// Row to select after a rebuild (previous selection when null). - /// when the list was rebuilt. - private bool PopulateEntries(IEnumerable entries, string title, string? selectUuid = null) - { - List visible = entries.ToList(); - if (_onlyTotp) - { - visible = visible.Where(entry => entry.HasTotp).ToList(); - } - visible = _entrySort switch - { - "modified" => visible.OrderByDescending(entry => entry.ModifiedUnix).ToList(), - "group" => visible - .OrderBy(entry => _groupNames.GetValueOrDefault(entry.GroupUuid, string.Empty), - StringComparer.CurrentCultureIgnoreCase) - .ThenBy(entry => entry.Title, StringComparer.CurrentCultureIgnoreCase) - .ToList(), - _ => visible - .OrderBy(entry => entry.Title, StringComparer.CurrentCultureIgnoreCase) - .ToList(), - }; - - string fingerprint = EntryListFingerprint(visible, title); - if (fingerprint == _lastEntryFingerprint && Entries.Count == visible.Count) - { - // Same rows in the same order: keep the items (and the scroll offset). - CurrentGroupTitle.Text = title; - UpdateEntryCountText(); - if (selectUuid is not null) - { - SelectEntryRow(selectUuid); - } - return false; - } - - string? keepUuid = selectUuid ?? (EntryList.SelectedItem as EntryItem)?.Uuid; - Entries.Clear(); - foreach (EntrySummaryDto entry in visible) - { - string groupName = _groupNames.GetValueOrDefault(entry.GroupUuid, "Vault"); - Entries.Add(new EntryItem(entry, groupName)); - } - _lastEntryFingerprint = fingerprint; - CurrentGroupTitle.Text = title; - UpdateEntryCountText(); - EmptyListHint.Text = _onlyTotp - ? "No entries with TOTP in this view. Clear the filter to see all entries." - : "Create the first entry with New."; - if (keepUuid is not null) - { - SelectEntryRow(keepUuid); - } - if (!ReferenceEquals(EntryList.SelectedItem, null)) - { - return true; - } - if (Entries.Count > 0) - { - EntryList.SelectedIndex = 0; - } - else - { - EntryList.SelectedIndex = -1; - ClearDetail(); - } - return true; - } - - private void UpdateEntryCountText() - { - EntryCountText.Text = $"{Entries.Count} {(Entries.Count == 1 ? "entry" : "entries")}" + - (_onlyTotp ? " · TOTP only" : string.Empty); - EmptyListState.Visibility = Entries.Count == 0 ? Visibility.Visible : Visibility.Collapsed; - } - - private void SelectEntryRow(string uuid) - { - EntryItem? item = Entries.FirstOrDefault(entry => entry.Uuid == uuid); - if (item is not null && !ReferenceEquals(EntryList.SelectedItem, item)) - { - EntryList.SelectedItem = item; - } - } - - /// - /// Cheap identity of the rendered rows; rebuilt lists with the same identity - /// are not re-rendered, so scroll position and selection survive merges and - /// moves that do not change what the user sees in the middle column. - /// - private static string EntryListFingerprint(List visible, string title) - { - var builder = new System.Text.StringBuilder(title); - foreach (EntrySummaryDto entry in visible) - { - builder.Append('\n') - .Append(entry.Uuid).Append('|') - .Append(entry.GroupUuid).Append('|') - .Append(entry.Title).Append('|') - .Append(entry.Username).Append('|') - .Append(entry.Url).Append('|') - .Append(entry.HasTotp ? '1' : '0'); - } - return builder.ToString(); - } - - /// - /// Applies a successful drag-move to the middle column in place instead of - /// reloading the whole vault: the moved row either keeps its position (All - /// entries / search view, group label updated) or is removed from the group - /// view it just left. Neither path touches the scroll position. - /// - private void ApplyEntryMovedLocally(string entryUuid, string? sourceGroupUuid, - string targetGroupUuid, string targetGroupName) - { - string targetName = _groupNames.GetValueOrDefault(targetGroupUuid, targetGroupName); - EntryItem? item = Entries.FirstOrDefault(entry => entry.Uuid == entryUuid); - if (item is not null) - { - bool searchActive = SearchBox.Text.Trim().Length > 0; - if (_selectedGroupUuid is null || searchActive) - { - item.UpdateGroup(targetGroupUuid, targetName); - } - else if (sourceGroupUuid == _selectedGroupUuid) - { - int index = Entries.IndexOf(item); - bool wasSelected = ReferenceEquals(EntryList.SelectedItem, item); - Entries.Remove(item); - if (wasSelected && Entries.Count > 0) - { - EntryList.SelectedIndex = Math.Min(index, Entries.Count - 1); - } - else if (Entries.Count == 0) - { - EntryList.SelectedIndex = -1; - ClearDetail(); - } - UpdateEntryCountText(); - } - } - if (_currentFull is not null && _currentFull.Uuid == entryUuid) - { - _currentFull.GroupUuid = targetGroupUuid; - } - if (sourceGroupUuid != targetGroupUuid) - { - AdjustGroupCount(sourceGroupUuid, -1); - AdjustGroupCount(targetGroupUuid, 1); - PopulateNavigation(_selectedGroupUuid); - } - RefreshEntryListFingerprint(CurrentGroupTitle.Text); - } - - /// - /// Recomputes the "already rendered" identity after an in-place row update, - /// so a following reload does not rebuild the whole list for the same rows. - /// - private void RefreshEntryListFingerprint(string title) - { - var builder = new System.Text.StringBuilder(title); - foreach (EntryItem item in Entries) - { - builder.Append('\n') - .Append(item.Uuid).Append('|') - .Append(item.GroupUuid).Append('|') - .Append(item.Title).Append('|') - .Append(item.Username).Append('|') - .Append(item.Url).Append('|') - .Append(item.HasTotp ? '1' : '0'); - } - _lastEntryFingerprint = builder.ToString(); - } - - private void AdjustGroupCount(string? groupUuid, int delta) - { - if (groupUuid is null || delta == 0) - { - return; - } - for (int index = 0; index < Groups.Count; index++) - { - GroupItem group = Groups[index]; - if (group.Uuid == groupUuid) - { - Groups[index] = new GroupItem(group.Uuid, group.Name, - Math.Max(0, group.CountValue + delta), group.Glyph); - return; - } - } - } - - private void ListOptionsButton_Click(object sender, RoutedEventArgs e) - { - var flyout = new MenuFlyout(); - void AddSort(string label, string value) - { - var item = new RadioMenuFlyoutItem - { - Text = label, - GroupName = "entry-sort", - IsChecked = _entrySort == value, - }; - item.Click += (_, _) => - { - _entrySort = value; - RefreshEntries(); - }; - flyout.Items.Add(item); - } - AddSort("Sort by title", "title"); - AddSort("Sort by recently modified", "modified"); - AddSort("Sort by group", "group"); - flyout.Items.Add(new MenuFlyoutSeparator()); - var totpOnly = new ToggleMenuFlyoutItem - { - Text = "Only entries with TOTP", - IsChecked = _onlyTotp, - }; - totpOnly.Click += (_, _) => - { - _onlyTotp = totpOnly.IsChecked; - RefreshEntries(); - }; - flyout.Items.Add(totpOnly); - flyout.Placement = FlyoutPlacementMode.Bottom; - flyout.ShowAt(ListOptionsButton); - } - - private async void RefreshEntries() - { - try - { - await LoadSelectedGroupAsync(); - } - catch (Exception ex) - { - ShowToast(ex.Message, InfoBarSeverity.Error); - } - } - - private async void NavView_SelectionChanged(NavigationView sender, - NavigationViewSelectionChangedEventArgs args) - { - if (_suppressNav || - args.SelectedItemContainer is not NavigationViewItem item || - item.Tag is not string tag) - { - return; - } - // Footer actions are invoked explicitly, never treated as groups. - if (tag is "settings" or "sync" or "backups" or "lock") - { - return; - } - ClosePanels(); - _selectedGroupUuid = tag == "all" ? null : tag; - try - { - await LoadSelectedGroupAsync(); - } - catch (Exception ex) - { - ShowToast(ex.Message, InfoBarSeverity.Error); - } - } - - private void HamburgerButton_Click(object sender, RoutedEventArgs e) - { - NavView.IsPaneOpen = !NavView.IsPaneOpen; - } - - private void TitleBarButton_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e) - { - // Buttons in the title bar must never fall through to the caption's - // double-click maximize/restore behavior. - e.Handled = true; - } - - private async Task LoadSelectedGroupAsync() - { - string? query = SearchBox.Text.Trim(); - if (query.Length > 0) - { - List matches = await _core.SearchAsync(query); - IEnumerable results = matches.Select(match => match.Entry); - if (_recycleBinGroupUuid is not null) - { - bool viewingRecycleBin = _selectedGroupUuid == _recycleBinGroupUuid; - results = viewingRecycleBin - ? results.Where(entry => entry.GroupUuid == _recycleBinGroupUuid) - : results.Where(entry => entry.GroupUuid != _recycleBinGroupUuid); - } - PopulateEntries(results, "Search results"); - return; - } - List entries = await _core.ListEntriesAsync(_selectedGroupUuid); - if (_selectedGroupUuid is null && _recycleBinGroupUuid is not null) - { - entries = entries - .Where(entry => entry.GroupUuid != _recycleBinGroupUuid) - .ToList(); - } - string title = _selectedGroupUuid is null - ? "All entries" - : _groupNames.GetValueOrDefault(_selectedGroupUuid, "Entries"); - PopulateEntries(entries, title); - } - - private async void SearchBox_TextChanged(AutoSuggestBox sender, - AutoSuggestBoxTextChangedEventArgs args) - { - if (args.Reason != AutoSuggestionBoxTextChangeReason.UserInput || !_core.IsOpen) - { - return; - } - _searchCts?.Cancel(); - _searchCts = new CancellationTokenSource(); - CancellationToken token = _searchCts.Token; - try - { - await Task.Delay(220, token); - } - catch (OperationCanceledException) - { - return; - } - try - { - await LoadSelectedGroupAsync(); - } - catch (Exception ex) - { - if (!token.IsCancellationRequested) - { - ShowToast(ex.Message, InfoBarSeverity.Error); - } - } - } - - private async void SyncStatusButton_Click(object sender, RoutedEventArgs e) - { - if (!IsSyncConfigured) - { - ShowToast("Configure WebDAV in Settings first.", InfoBarSeverity.Informational); - SettingsButton_Click(this, new RoutedEventArgs()); - return; - } - await SyncAsync(); - } - - private void NavView_ItemInvoked(NavigationView sender, - NavigationViewItemInvokedEventArgs args) - { - if (args.InvokedItemContainer is not NavigationViewItem item || - item.Tag is not string tag) - { - return; - } - ClosePanels(); - switch (tag) - { - case "sync": - SyncStatusButton_Click(this, new RoutedEventArgs()); - break; - case "backups": - _ = ShowBackupsAsync(); - break; - case "lock": - LockButton_Click(this, new RoutedEventArgs()); - break; - case "settings": - SettingsButton_Click(this, new RoutedEventArgs()); - break; - } - } - - // -------------------------------------------------------------- detail - - private async void EntryList_SelectionChanged(object sender, SelectionChangedEventArgs e) - { - if (EntryList.SelectedItem is not EntryItem item) - { - ClearDetail(); - return; - } - try - { - await ShowEntryAsync(item); - } - catch (Exception ex) - { - ShowToast(ex.Message, InfoBarSeverity.Error); - } - } - - private void EntryList_DragItemsStarting(object sender, DragItemsStartingEventArgs e) - { - if (e.Items.Count == 0 || e.Items[0] is not EntryItem entry) - { - e.Cancel = true; - return; - } - e.Data.SetText(entry.Uuid); - e.Data.RequestedOperation = DataPackageOperation.Move; - e.Data.Properties.Title = entry.Title; - } - - private void EntryList_RightTapped(object sender, RightTappedRoutedEventArgs e) - { - if (e.OriginalSource is not DependencyObject source) - { - return; - } - ListViewItem? container = FindAncestor(source); - if (container?.DataContext is not EntryItem entry) - { - return; - } - EntryList.SelectedItem = entry; - BuildEntryContextMenu(entry).ShowAt(container); - e.Handled = true; - } - - private MenuFlyout BuildEntryContextMenu(EntryItem entry) - { - var flyout = new MenuFlyout(); - void Add(string text, string glyph, Func action, bool danger = false) - { - var item = new MenuFlyoutItem - { - Text = text, - Icon = new FontIcon { Glyph = glyph, FontSize = 12 }, - }; - if (danger) - { - item.Foreground = - (Brush)Application.Current.Resources["SystemFillColorCriticalBrush"]; - } - item.Click += async (_, _) => - { - try - { - await action(); - } - catch (Exception ex) - { - ShowToast(ex.Message, InfoBarSeverity.Error); - } - }; - flyout.Items.Add(item); - } - - if (!string.IsNullOrWhiteSpace(entry.Username)) - { - Add("Copy username", "\uE8C8", () => - { - CopyText(entry.Username, "Username copied"); - return Task.CompletedTask; - }); - } - Add("Copy password", "\uE8C8", () => CopyEntryPasswordAsync(entry)); - if (!string.IsNullOrWhiteSpace(entry.Url)) - { - Add("Copy website", "\uE8C8", () => - { - CopyText(entry.Url, "Website copied"); - return Task.CompletedTask; - }); - Add("Open website", "\uE8A7", () => OpenEntryUrlAsync(entry)); - } - if (entry.HasTotp) - { - Add("Copy TOTP", "\uE8C8", () => CopyEntryTotpAsync(entry)); - } - flyout.Items.Add(new MenuFlyoutSeparator()); - Add("Edit entry", "\uE70F", () => RunEntryActionAsync(entry, () => - EditEntryButton_Click(this, new RoutedEventArgs()))); - Add("Move entry", "\uE8DE", () => RunEntryActionAsync(entry, () => - MoveEntryButton_Click(this, new RoutedEventArgs()))); - Add("Delete entry", "\uE74D", () => RunEntryActionAsync(entry, () => - DeleteEntryButton_Click(this, new RoutedEventArgs())), danger: true); - return flyout; - } - - private async Task CopyEntryPasswordAsync(EntryItem entry) - { - EntryFullDto full = await _core.GetEntryAsync(entry.Uuid); - CopyText(full.PasswordSecret, "Password copied"); - } - - private async Task CopyEntryTotpAsync(EntryItem entry) - { - TotpCodeDto? code = await _core.TotpCodeAsync(entry.Uuid); - if (code is null) - { - ShowToast("No TOTP configured for this entry.", InfoBarSeverity.Warning); - return; - } - CopyText(code.Code, "One-time code copied"); - } - - private async Task OpenEntryUrlAsync(EntryItem entry) - { - if (Uri.TryCreate(entry.Url, UriKind.Absolute, out Uri? uri)) - { - await Launcher.LaunchUriAsync(uri); - } - } - - private async Task RunEntryActionAsync(EntryItem entry, Action action) - { - await ShowEntryAsync(entry); - action(); - } - - private static T? FindAncestor(DependencyObject? node) where T : DependencyObject - { - while (node is not null) - { - if (node is T match) - { - return match; - } - node = VisualTreeHelper.GetParent(node); - } - return null; - } - - private async Task ShowEntryAsync(EntryItem summary) - { - int generation = ++_showGeneration; - _currentSummary = summary; - _passwordVisible = false; - EntryFullDto full = await _core.GetEntryAsync(summary.Uuid); - if (generation != _showGeneration) - { - return; - } - _currentFull = full; - DetailTitle.Text = full.Title; - string groupName = _groupNames.GetValueOrDefault(full.GroupUuid, "Vault"); - // The website is already a field below; keep the header to a short - // group label so long URLs do not get awkwardly ellipsized up here. - DetailSubtitle.Text = groupName; - DetailUsername.Text = full.Username; - DetailUrl.Text = full.Url; - DetailNotes.Text = full.Notes; - DetailPassword.Text = "••••••••••••"; - DetailTags.Text = full.Tags.Count > 0 ? string.Join(" · ", full.Tags) : string.Empty; - - CustomFieldDto? custom = full.CustomFields.FirstOrDefault(field => !IsTotpField(field.Key)); - CustomFieldsSection.Visibility = custom is null ? Visibility.Collapsed : Visibility.Visible; - CustomFieldsDivider.Visibility = CustomFieldsSection.Visibility; - CustomFieldName.Text = custom?.Key ?? string.Empty; - CustomFieldValue.Text = custom?.Value ?? string.Empty; - - bool hasUsername = !string.IsNullOrWhiteSpace(full.Username); - bool hasPassword = !string.IsNullOrEmpty(full.PasswordSecret); - bool hasUrl = !string.IsNullOrWhiteSpace(full.Url); - bool hasTags = full.Tags.Count > 0; - bool hasNotes = !string.IsNullOrWhiteSpace(full.Notes); - bool hasCustom = custom is not null; - bool hasTotp = full.Totp is not null; - - UsernameRow.Visibility = hasUsername ? Visibility.Visible : Visibility.Collapsed; - PasswordRow.Visibility = hasPassword ? Visibility.Visible : Visibility.Collapsed; - UrlRow.Visibility = hasUrl ? Visibility.Visible : Visibility.Collapsed; - TagsRow.Visibility = hasTags ? Visibility.Visible : Visibility.Collapsed; - NotesSection.Visibility = hasNotes ? Visibility.Visible : Visibility.Collapsed; - NotesDivider.Visibility = NotesSection.Visibility; - UsernameDivider.Visibility = hasUsername && - (hasPassword || hasUrl || hasTags) - ? Visibility.Visible - : Visibility.Collapsed; - PasswordDivider.Visibility = hasPassword && - (hasUrl || hasTags) - ? Visibility.Visible - : Visibility.Collapsed; - UrlDivider.Visibility = hasUrl && hasTags - ? Visibility.Visible - : Visibility.Collapsed; - - TotpSection.Visibility = hasTotp ? Visibility.Visible : Visibility.Collapsed; - TotpDivider.Visibility = TotpSection.Visibility; - if (hasTotp) - { - TotpCode.FontSize = 24; - TotpRemainingText.Visibility = Visibility.Visible; - TotpProgress.Visibility = Visibility.Visible; - // Never show or copy a code that belongs to the previously selected - // entry while the first code for this entry is being fetched. - ResetTotpDisplayState(); - await UpdateTotpAsync(generation); - } - else - { - TotpCode.FontSize = 13; - TotpCode.Text = string.Empty; - TotpRemainingText.Text = string.Empty; - TotpRemainingText.Visibility = Visibility.Collapsed; - TotpProgress.Value = 0; - TotpProgress.Visibility = Visibility.Collapsed; - ResetTotpDisplayState(); - } - AnimateDetailContent(); - } - - private void ClearDetail() - { - _currentFull = null; - _currentSummary = null; - ResetTotpDisplayState(); - DetailTitle.Text = "Select an entry"; - DetailSubtitle.Text = string.Empty; - DetailUsername.Text = string.Empty; - DetailPassword.Text = string.Empty; - DetailUrl.Text = string.Empty; - DetailTags.Text = string.Empty; - DetailNotes.Text = string.Empty; - UsernameRow.Visibility = Visibility.Collapsed; - PasswordRow.Visibility = Visibility.Collapsed; - UrlRow.Visibility = Visibility.Collapsed; - TagsRow.Visibility = Visibility.Collapsed; - UsernameDivider.Visibility = Visibility.Collapsed; - PasswordDivider.Visibility = Visibility.Collapsed; - UrlDivider.Visibility = Visibility.Collapsed; - CustomFieldsSection.Visibility = Visibility.Collapsed; - CustomFieldsDivider.Visibility = Visibility.Collapsed; - NotesSection.Visibility = Visibility.Collapsed; - NotesDivider.Visibility = Visibility.Collapsed; - TotpSection.Visibility = Visibility.Collapsed; - TotpDivider.Visibility = Visibility.Collapsed; - TotpProgress.Value = 0; - TotpRemainingText.Text = string.Empty; - TotpCode.Text = "—"; - } - - private async Task UpdateTotpAsync(int generation) - { - EntryFullDto? full = _currentFull; - if (full is null || full.Totp is null) - { - SetTotpUnavailable(); - return; - } - TotpCode.FontSize = 24; - TotpRemainingText.Visibility = Visibility.Visible; - TotpProgress.Visibility = Visibility.Visible; - DateTimeOffset now = DateTimeOffset.UtcNow; - long nowUnix = now.ToUnixTimeSeconds(); - if (_totpDisplayedCode is null || _totpDisplayedUuid != full.Uuid || - nowUnix >= _totpWindowEndUnix) - { - TotpCodeDto? prefetched = _totpPrefetchedCode; - long prefetchedTarget = _totpPrefetchTargetUnix; - int prefetchedPeriod = prefetched is null ? 0 : Math.Max(1, prefetched.Period); - if (prefetched is not null && _totpPrefetchedUuid == full.Uuid && - prefetchedTarget <= nowUnix && nowUnix < prefetchedTarget + prefetchedPeriod) - { - // The next window was already pre-fetched while fewer than 3s - // remained: switch exactly at the boundary without a core round - // trip, so the old code never shows one tick too long. - ActivateTotpCode(prefetched, - prefetchedTarget + Math.Max(1, prefetched.Period)); - _totpPrefetchedCode = null; - _totpPrefetchedUuid = null; - _totpPrefetchInFlight = false; - } - else - { - _totpPrefetchedCode = null; - _totpPrefetchedUuid = null; - _totpPrefetchInFlight = false; - long requestedAtUnix = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); - TotpCodeDto? code = await _core.TotpCodeAsync(full.Uuid); - if (generation != _showGeneration || _currentFull?.Uuid != full.Uuid) - { - return; - } - if (code is null) - { - SetTotpUnavailable(); - return; - } - ActivateTotpCode(code, requestedAtUnix + Math.Max(1, code.Remaining)); - } - } - nowUnix = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); - UpdateTotpCountdown(nowUnix); - if (_totpDisplayedCode is null || _totpDisplayedUuid != full.Uuid) - { - return; - } - int period = Math.Max(1, _totpDisplayedCode.Period); - int remaining = (int)Math.Clamp(_totpWindowEndUnix - nowUnix, 0, period); - if (remaining < 3 && _totpWindowEndUnix != long.MaxValue && - _totpPrefetchedCode is null && !_totpPrefetchInFlight) - { - // Pre-fetch the next window now; the timer tick scheduled at the - // boundary will swap it in immediately. - _totpPrefetchInFlight = true; - _ = PrefetchTotpAsync(full.Uuid, _totpWindowEndUnix, period, generation); - } - ScheduleTotpTimerTick(DateTimeOffset.UtcNow); - } - - private async Task PrefetchTotpAsync(string uuid, long targetUnix, int period, - int generation) - { - try - { - TotpCodeDto? next = await _core.TotpCodeAsync(uuid, targetUnix); - if (next is null || generation != _showGeneration || - _currentFull?.Uuid != uuid) - { - return; - } - long nowUnix = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); - if (nowUnix < targetUnix) - { - _totpPrefetchedCode = next; - _totpPrefetchedUuid = uuid; - _totpPrefetchTargetUnix = targetUnix; - } - else if (nowUnix < targetUnix + Math.Max(1, period) && - _totpWindowEndUnix <= nowUnix) - { - // The boundary arrived while this request was in flight; the - // prefetched code is still the live window, adopt it now. - ActivateTotpCode(next, targetUnix + Math.Max(1, period)); - } - } - catch (Exception ex) - { - AppLog.Warn($"TOTP prefetch failed: {ex.Message}"); - } - finally - { - _totpPrefetchInFlight = false; - } - } - - private void ActivateTotpCode(TotpCodeDto code, long windowEndUnix) - { - _totpDisplayedCode = code; - _totpDisplayedUuid = _currentFull?.Uuid; - _currentTotpCode = code.Code; - _totpWindowEndUnix = windowEndUnix; - UpdateTotpCountdown(DateTimeOffset.UtcNow.ToUnixTimeSeconds()); - } - - private void UpdateTotpCountdown(long nowUnix) - { - TotpCodeDto? code = _totpDisplayedCode; - if (code is null) - { - return; - } - int period = Math.Max(1, code.Period); - int remaining = (int)Math.Clamp(_totpWindowEndUnix - nowUnix, 0, period); - int digits = code.Digits > 0 ? code.Digits : 6; - TotpCode.Text = FormatTotp(code.Code, digits); - TotpRemainingText.Text = $"Refreshes in {remaining}s"; - TotpProgress.Maximum = period; - TotpProgress.Value = period - remaining; - } - - private void ScheduleTotpTimerTick(DateTimeOffset now) - { - if (_totpWindowEndUnix == long.MaxValue) - { - _totpTimer.Interval = TimeSpan.FromSeconds(1); - return; - } - DateTimeOffset boundary = DateTimeOffset.FromUnixTimeSeconds(_totpWindowEndUnix); - TimeSpan untilBoundary = boundary - now; - TimeSpan interval = untilBoundary > TimeSpan.Zero && - untilBoundary < TimeSpan.FromSeconds(1) - ? untilBoundary + TimeSpan.FromMilliseconds(15) - : TimeSpan.FromSeconds(1); - if (Math.Abs((_totpTimer.Interval - interval).TotalMilliseconds) >= 10) - { - // Changing the interval restarts the timer, so the next tick lands - // on (or just after) the TOTP window boundary. - _totpTimer.Interval = interval; - } - } - - private void SetTotpUnavailable() - { - ResetTotpDisplayState(); - TotpCode.FontSize = 13; - TotpCode.Text = "No TOTP configured"; - TotpRemainingText.Text = string.Empty; - TotpRemainingText.Visibility = Visibility.Collapsed; - TotpProgress.Value = 0; - TotpProgress.Visibility = Visibility.Collapsed; - } - - private void ResetTotpDisplayState() - { - _totpDisplayedCode = null; - _totpDisplayedUuid = null; - _totpPrefetchedCode = null; - _totpPrefetchedUuid = null; - _totpWindowEndUnix = long.MaxValue; - _totpPrefetchTargetUnix = long.MinValue; - _totpPrefetchInFlight = false; - _currentTotpCode = null; - if (_totpTimer.IsEnabled && _totpTimer.Interval != TimeSpan.FromSeconds(1)) - { - _totpTimer.Interval = TimeSpan.FromSeconds(1); - } - } - - private static string FormatTotp(string code, int digits) - { - if (digits == 8 && code.Length == 8) - { - return $"{code[..4]} {code[4..]}"; - } - if (code.Length == 6) - { - return $"{code[..3]} {code[3..]}"; - } - return code; - } - - private static bool IsTotpField(string key) - => key == "otp" - || key == "TOTP Seed" - || key == "TOTP Settings" - || key.StartsWith("TimeOtp-", StringComparison.OrdinalIgnoreCase); - - private void RevealPasswordButton_Click(object sender, RoutedEventArgs e) - { - if (_currentFull is null) - { - return; - } - _passwordVisible = !_passwordVisible; - DetailPassword.Text = _passwordVisible - ? _currentFull.PasswordSecret - : "••••••••••••"; - } - - private void CopyUsernameButton_Click(object sender, RoutedEventArgs e) - { - if (_currentFull is not null) - { - CopyText(_currentFull.Username, "Username copied"); - } - } - - private void CopyPasswordButton_Click(object sender, RoutedEventArgs e) - { - if (_currentFull is not null) - { - CopyText(_currentFull.PasswordSecret, "Password copied"); - } - } - - private void CopyUrlButton_Click(object sender, RoutedEventArgs e) - { - if (_currentFull is not null) - { - CopyText(_currentFull.Url, "URL copied"); - } - } - - private void CopyTotpButton_Click(object sender, RoutedEventArgs e) - { - if (!string.IsNullOrEmpty(_currentTotpCode)) - { - CopyText(_currentTotpCode, "One-time code copied"); - } - } - - private void CopyCustomFieldButton_Click(object sender, RoutedEventArgs e) - { - if (!string.IsNullOrEmpty(CustomFieldValue.Text)) - { - CopyText(CustomFieldValue.Text, "Custom field copied"); - } - } - - private void CopyText(string text, string label) - { - var package = new DataPackage(); - package.SetText(text); - // Keep copied secrets out of Win+V history and cloud clipboard where - // Windows honors the request. - var options = new ClipboardContentOptions - { - IsAllowedInHistory = false, - IsRoamable = false, - }; - try - { - Clipboard.SetContentWithOptions(package, options); - } - catch - { - // Older shells may not support content options; plain copy still works. - Clipboard.SetContent(package); - } - _lastClipboardText = text; - _clipboardTimer.Stop(); - if (Settings.ClearClipboardAfter30Seconds) - { - _clipboardTimer.Start(); - ShowToast($"{label} — clears in 30 seconds", InfoBarSeverity.Success); - } - else - { - ShowToast(label, InfoBarSeverity.Success); - } - } - - private async void OpenUrlButton_Click(object sender, RoutedEventArgs e) - { - if (_currentFull is null) - { - return; - } - if (Uri.TryCreate(_currentFull.Url, UriKind.Absolute, out Uri? uri)) - { - await Launcher.LaunchUriAsync(uri); - } - } - - // ---------------------------------------------------------------- CRUD - - private async void NewEntryButton_Click(object sender, RoutedEventArgs e) - { - if (!_core.IsOpen) - { - return; - } - var groupChoice = new ComboBox - { - Header = "Group", - ItemsSource = _selectableGroups, - DisplayMemberPath = "Name", - HorizontalAlignment = HorizontalAlignment.Stretch, - }; - groupChoice.SelectedItem = _selectableGroups.FirstOrDefault(group => - group.Uuid == (_selectedGroupUuid ?? _selectableGroups.FirstOrDefault()?.Uuid)); - - var title = new TextBox { Header = "Title", PlaceholderText = "Entry name" }; - var username = new TextBox { Header = "Username", PlaceholderText = "name@example.com" }; - var password = new PasswordBox { Header = "Password", PasswordRevealMode = PasswordRevealMode.Peek }; - var url = new TextBox { Header = "Website", PlaceholderText = "https://" }; - var notes = new TextBox - { - Header = "Notes", - AcceptsReturn = true, - TextWrapping = TextWrapping.Wrap, - Height = 84, - }; - var content = new StackPanel { Spacing = 14 }; - content.Children.Add(groupChoice); - content.Children.Add(title); - content.Children.Add(username); - content.Children.Add(BuildPasswordRow(password)); - content.Children.Add(url); - content.Children.Add(notes); - UIElement form = CreateFormSection("Details", content); - if (await ShowDetailPanelAsync("New entry", form, "Create", - primaryGlyph: "\uE710") != - RightPanelResult.Primary || - groupChoice.SelectedItem is not GroupDto group) - { - return; - } - try - { - string uuid = await _core.CreateEntryAsync(group.Uuid, - string.IsNullOrWhiteSpace(title.Text) ? "Untitled entry" : title.Text.Trim(), - username.Text.Trim(), password.Password, url.Text.Trim(), notes.Text); - await SaveAsync(); - await ReloadVaultAsync(uuid, preserveScroll: false); - ShowToast("Entry created and saved", InfoBarSeverity.Success); - } - catch (Exception ex) - { - ShowToast(ex.Message, InfoBarSeverity.Error); - } - } - - private async void EditEntryButton_Click(object sender, RoutedEventArgs e) - { - if (_currentFull is null) - { - return; - } - var title = new TextBox { Header = "Title", Text = _currentFull.Title }; - var username = new TextBox { Header = "Username", Text = _currentFull.Username }; - var password = new PasswordBox - { - Header = "Password", - Password = _currentFull.PasswordSecret, - PasswordRevealMode = PasswordRevealMode.Peek, - }; - var url = new TextBox { Header = "Website", Text = _currentFull.Url }; - var tags = new TextBox - { - Header = "Tags (comma-separated)", - Text = string.Join(", ", _currentFull.Tags), - }; - var notes = new TextBox - { - Header = "Notes", - Text = _currentFull.Notes, - AcceptsReturn = true, - TextWrapping = TextWrapping.Wrap, - Height = 84, - }; - TotpConfigDto? existingTotp = _currentFull.Totp; - var totpSecret = new TextBox - { - Header = "Base32 secret", - Text = existingTotp?.SecretBase32 ?? string.Empty, - PlaceholderText = "JBSWY3DPEHPK3PXP", - FontFamily = new FontFamily("Consolas"), - }; - var totpAlgorithm = new ComboBox - { - Header = "Algorithm", - ItemsSource = new[] { "SHA1", "SHA256", "SHA512" }, - SelectedItem = existingTotp?.Algorithm ?? "SHA1", - }; - var totpDigits = new ComboBox - { - Header = "Digits", - ItemsSource = new[] { "6", "8" }, - SelectedItem = (existingTotp?.Digits ?? 6).ToString(), - }; - var totpPeriod = new NumberBox - { - Header = "Period (seconds)", - Value = existingTotp?.Period ?? 30, - Minimum = 1, - Maximum = 300, - }; - var totpHint = new TextBlock - { - Text = existingTotp is null - ? "No TOTP yet. Paste or import a Base32 secret to add one." - : "Leave the secret empty and save to remove TOTP.", - FontSize = 12, - TextWrapping = TextWrapping.Wrap, - Foreground = (Brush)Application.Current.Resources["TextFillColorSecondaryBrush"], - }; - var totpStatus = new TextBlock - { - FontSize = 11, - TextWrapping = TextWrapping.Wrap, - Foreground = (Brush)Application.Current.Resources["TextFillColorSecondaryBrush"], - }; - var totpFields = new StackPanel { Spacing = 12 }; - totpFields.Children.Add(totpHint); - totpFields.Children.Add(BuildTotpImportRow( - totpSecret, totpAlgorithm, totpDigits, totpPeriod, totpStatus)); - totpFields.Children.Add(totpSecret); - totpFields.Children.Add(totpAlgorithm); - totpFields.Children.Add(totpDigits); - totpFields.Children.Add(totpPeriod); - - var content = new StackPanel { Spacing = 14 }; - content.Children.Add(title); - content.Children.Add(username); - content.Children.Add(BuildPasswordRow(password)); - content.Children.Add(url); - content.Children.Add(tags); - content.Children.Add(notes); - var form = new StackPanel { Spacing = 20 }; - form.Children.Add(CreateFormSection("Details", content)); - form.Children.Add(CreateFormSection("One-time password", totpFields)); - if (await ShowDetailPanelAsync("Edit entry", form, "Save") != - RightPanelResult.Primary) - { - return; - } - try - { - List tagList = tags.Text - .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) - .Distinct(StringComparer.OrdinalIgnoreCase) - .ToList(); - string uuid = _currentFull.Uuid; - await _core.UpdateEntryAsync(uuid, title.Text.Trim(), - username.Text.Trim(), password.Password, url.Text.Trim(), notes.Text, tagList); - string totpValue = totpSecret.Text.Trim(); - if (totpValue.Length == 0) - { - if (existingTotp is not null) - { - await _core.TotpDeleteAsync(uuid); - } - } - else - { - await _core.TotpSetAsync(uuid, new TotpConfigDto - { - SecretBase32 = totpValue, - Algorithm = totpAlgorithm.SelectedItem as string ?? "SHA1", - Digits = int.TryParse(totpDigits.SelectedItem as string, - out int parsedDigits) - ? parsedDigits - : 6, - Period = (int)Math.Clamp(totpPeriod.Value, 1, 300), - Encoder = "totp", - }); - } - await SaveAsync(); - await ReloadVaultAsync(uuid); - ShowToast("Entry updated and saved", InfoBarSeverity.Success); - } - catch (Exception ex) - { - ShowToast(ex.Message, InfoBarSeverity.Error); - } - } - - private async void MoveEntryButton_Click(object sender, RoutedEventArgs e) - { - if (_currentFull is null || _selectableGroups.Count == 0) - { - return; - } - var choices = new ComboBox - { - Header = "Move to group", - ItemsSource = _selectableGroups, - DisplayMemberPath = "Name", - HorizontalAlignment = HorizontalAlignment.Stretch, - }; - choices.SelectedItem = _selectableGroups.FirstOrDefault(group => - group.Uuid == _currentFull.GroupUuid) ?? _selectableGroups[0]; - if (await ShowDetailPanelAsync("Move entry", choices, "Move", - primaryGlyph: "\uE8DE") != - RightPanelResult.Primary || - choices.SelectedItem is not GroupDto target || - _currentFull is null) - { - return; - } - string uuid = _currentFull.Uuid; - try - { - await _core.MoveEntryAsync(uuid, target.Uuid); - await SaveAsync(); - _selectedGroupUuid = target.Uuid; - await ReloadVaultAsync(uuid); - ShowToast($"Moved to {target.Name}", InfoBarSeverity.Success); - } - catch (Exception ex) - { - ShowToast(ex.Message, InfoBarSeverity.Error); - } - } - - private async void DeleteEntryButton_Click(object sender, RoutedEventArgs e) - { - if (_currentFull is null) - { - return; - } - string title = _currentFull.Title; - string uuid = _currentFull.Uuid; - var dialog = new ContentDialog - { - Title = "Delete entry?", - Content = $"\"{title}\" will be moved to the recycle bin.", - PrimaryButtonText = "Delete", - CloseButtonText = "Cancel", - DefaultButton = ContentDialogButton.Close, - XamlRoot = Root.XamlRoot, - }; - if (await dialog.ShowAsync() != ContentDialogResult.Primary) - { - return; - } - try - { - await _core.DeleteEntryAsync(uuid); - await SaveAsync(); - await ReloadVaultAsync(null); - ShowToast("Entry moved to the recycle bin", InfoBarSeverity.Informational); - } - catch (Exception ex) - { - ShowToast(ex.Message, InfoBarSeverity.Error); - } - } - - private static UIElement CreateFormSection(string label, UIElement content) - { - var card = new Border - { - Background = (Brush)Application.Current.Resources["CardBackgroundFillColorDefaultBrush"], - BorderBrush = (Brush)Application.Current.Resources["CardStrokeColorDefaultBrush"], - BorderThickness = new Thickness(1), - CornerRadius = new CornerRadius(10), - Padding = new Thickness(18), - Child = content, - }; - var section = new StackPanel { Spacing = 8 }; - section.Children.Add(new TextBlock - { - Text = label, - Style = (Style)Application.Current.Resources["SectionLabel"], - Margin = new Thickness(2, 0, 0, 0), - }); - section.Children.Add(card); - return section; - } - - private StackPanel BuildTotpImportRow(TextBox secret, ComboBox algorithm, - ComboBox digits, NumberBox period, TextBlock status) - { - var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 }; - var importFile = new Button - { - Content = CreateIconLabel("Import QR image…", "\uE8B7"), - }; - var importClipboard = new Button - { - Content = CreateIconLabel("Paste QR / otpauth…", "\uE77F"), - }; - async Task ApplyImportedUriAsync(string? uri) - { - if (string.IsNullOrWhiteSpace(uri) || - !uri.StartsWith("otpauth://", StringComparison.OrdinalIgnoreCase)) - { - status.Text = "No otpauth QR code found. Paste a Base32 secret instead."; - return; - } - try - { - TotpConfigDto parsed = await _core.ParseTotpUriAsync(uri); - secret.Text = parsed.SecretBase32; - algorithm.SelectedItem = parsed.Algorithm; - digits.SelectedItem = parsed.Digits.ToString(); - period.Value = Math.Clamp(parsed.Period, 1, 300); - string account = string.Join(" / ", - new[] { parsed.Issuer, parsed.Account }.Where(value => - !string.IsNullOrWhiteSpace(value))); - status.Text = account.Length == 0 - ? "QR imported. Review the parameters and save." - : $"Imported {account}. Review and save."; - } - catch (Exception ex) - { - status.Text = $"Could not read otpauth URI: {ex.Message}"; - } - } - importFile.Click += async (_, _) => - { - try - { - var picker = new FileOpenPicker - { - SuggestedStartLocation = PickerLocationId.PicturesLibrary, - }; - foreach (string extension in new[] - { - ".png", ".jpg", ".jpeg", ".bmp", ".gif", ".tif", ".tiff", - }) - { - picker.FileTypeFilter.Add(extension); - } - WinRT.Interop.InitializeWithWindow.Initialize(picker, - WinRT.Interop.WindowNative.GetWindowHandle(this)); - StorageFile? file = await picker.PickSingleFileAsync(); - if (file is not null) - { - await ApplyImportedUriAsync(await QrDecoder.DecodeFileAsync(file)); - } - } - catch (Exception ex) - { - status.Text = $"QR image failed: {ex.Message}"; - } - }; - importClipboard.Click += async (_, _) => - { - try - { - await ApplyImportedUriAsync(await QrDecoder.DecodeClipboardAsync()); - } - catch (Exception ex) - { - status.Text = $"Clipboard QR failed: {ex.Message}"; - } - }; - row.Children.Add(importFile); - row.Children.Add(importClipboard); - var wrapper = new StackPanel { Spacing = 8 }; - wrapper.Children.Add(row); - wrapper.Children.Add(status); - return wrapper; - } - - private Grid BuildPasswordRow(PasswordBox password) - { - var row = new Grid { ColumnSpacing = 8 }; - row.ColumnDefinitions.Add( - new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - row.Children.Add(password); - var generate = new Button - { - Content = CreateIconLabel("Generate", "\uE945"), - VerticalAlignment = VerticalAlignment.Bottom, - }; - SetButtonAutomation(generate, "Generate password", - "Opens the password generator options", "GeneratePasswordButton"); - generate.Click += (_, _) => ShowPasswordGeneratorFlyout(generate, password); - Grid.SetColumn(generate, 1); - row.Children.Add(generate); - return row; - } - - private static ToggleSwitch CreateGeneratorToggle(string header, bool isOn) - { - var toggle = new ToggleSwitch - { - Header = header, - IsOn = isOn, - OnContent = "On", - OffContent = "Off", - HorizontalAlignment = HorizontalAlignment.Stretch, - }; - AutomationProperties.SetName(toggle, header); - return toggle; - } - - /// - /// Password generator options: length, character classes, ambiguous-character - /// exclusion and the resulting entropy. Every change regenerates through the - /// core and writes the result into the surrounding password box; the flyout - /// stays open so options can be tweaked before saving the entry. - /// - private void ShowPasswordGeneratorFlyout(Button anchor, PasswordBox target) - { - if (!_core.IsOpen) - { - ShowToast("Unlock the vault before generating a password.", InfoBarSeverity.Warning); - return; - } - var length = new NumberBox - { - Header = "Length", - Value = 20, - Minimum = 8, - Maximum = 64, - SmallChange = 1, - LargeChange = 8, - SpinButtonPlacementMode = NumberBoxSpinButtonPlacementMode.Inline, - HorizontalAlignment = HorizontalAlignment.Stretch, - }; - AutomationProperties.SetName(length, "Password length"); - AutomationProperties.SetAutomationId(length, "GeneratorLength"); - ToggleSwitch lowercase = CreateGeneratorToggle("Lowercase (a-z)", isOn: true); - ToggleSwitch uppercase = CreateGeneratorToggle("Uppercase (A-Z)", isOn: true); - ToggleSwitch digits = CreateGeneratorToggle("Digits (0-9)", isOn: true); - ToggleSwitch symbols = CreateGeneratorToggle("Symbols (!@#$…)", isOn: true); - ToggleSwitch excludeAmbiguous = - CreateGeneratorToggle("Exclude ambiguous characters (I l 1 O 0 o)", isOn: true); - AutomationProperties.SetAutomationId(lowercase, "GeneratorLowercase"); - AutomationProperties.SetAutomationId(uppercase, "GeneratorUppercase"); - AutomationProperties.SetAutomationId(digits, "GeneratorDigits"); - AutomationProperties.SetAutomationId(symbols, "GeneratorSymbols"); - AutomationProperties.SetAutomationId(excludeAmbiguous, "GeneratorExcludeAmbiguous"); - var entropy = new TextBlock - { - FontSize = 12, - TextWrapping = TextWrapping.Wrap, - Text = "Entropy: —", - }; - AutomationProperties.SetAutomationId(entropy, "GeneratorEntropy"); - var status = new TextBlock - { - FontSize = 11, - TextWrapping = TextWrapping.Wrap, - Text = "Options are applied by the core generator; the password is written " + - "into the field and Save stores it with the entry.", - Foreground = (Brush)Application.Current.Resources["TextFillColorTertiaryBrush"], - }; - var regenerate = new Button - { - Content = CreateIconLabel("Regenerate", "\uE72C"), - }; - SetButtonAutomation(regenerate, "Regenerate password", null, - "GeneratorRegenerateButton"); - var done = new Button { Content = "Done" }; - SetButtonAutomation(done, "Close password generator", null, "GeneratorDoneButton"); - var buttons = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 }; - buttons.Children.Add(regenerate); - buttons.Children.Add(done); - var content = new StackPanel { Spacing = 10, MinWidth = 300 }; - content.Children.Add(length); - content.Children.Add(lowercase); - content.Children.Add(uppercase); - content.Children.Add(digits); - content.Children.Add(symbols); - content.Children.Add(excludeAmbiguous); - content.Children.Add(entropy); - content.Children.Add(status); - content.Children.Add(buttons); - var flyout = new Flyout - { - Content = content, - Placement = FlyoutPlacementMode.Bottom, - }; - int generation = 0; - async Task RegenerateAsync(bool announce) - { - int ticket = ++generation; - int lengthValue = double.IsNaN(length.Value) - ? 20 - : (int)Math.Clamp(length.Value, 8, 64); - bool lowerOn = lowercase.IsOn; - bool upperOn = uppercase.IsOn; - bool digitsOn = digits.IsOn; - bool symbolsOn = symbols.IsOn; - if (!lowerOn && !upperOn && !digitsOn && !symbolsOn) - { - status.Text = "Select at least one character class."; - return; - } - try - { - PasswordGenerateDto generated = await _core.GeneratePasswordAsync( - lengthValue, excludeAmbiguous.IsOn, lowerOn, upperOn, digitsOn, symbolsOn); - if (ticket != generation) - { - return; - } - target.Password = generated.Password; - entropy.Text = $"Entropy: {generated.EntropyBits:F1} bits"; - if (announce) - { - status.Text = "Password generated. Save the entry to keep it."; - } - } - catch (Exception ex) - { - if (ticket == generation) - { - status.Text = "Generation failed: " + ex.Message; - } - } - } - void EnsureClassSelected(ToggleSwitch toggled) - { - if (toggled.IsOn || lowercase.IsOn || uppercase.IsOn || digits.IsOn || - symbols.IsOn) - { - return; - } - // At least one class must stay enabled: revert the change that would - // empty the alphabet (the core rejects an empty charset). - toggled.IsOn = true; - status.Text = "At least one character class must stay enabled."; - } - length.ValueChanged += (_, _) => _ = RegenerateAsync(false); - lowercase.Toggled += (_, _) => - { - EnsureClassSelected(lowercase); - _ = RegenerateAsync(false); - }; - uppercase.Toggled += (_, _) => - { - EnsureClassSelected(uppercase); - _ = RegenerateAsync(false); - }; - digits.Toggled += (_, _) => - { - EnsureClassSelected(digits); - _ = RegenerateAsync(false); - }; - symbols.Toggled += (_, _) => - { - EnsureClassSelected(symbols); - _ = RegenerateAsync(false); - }; - excludeAmbiguous.Toggled += (_, _) => _ = RegenerateAsync(false); - regenerate.Click += (_, _) => _ = RegenerateAsync(true); - flyout.Opened += (_, _) => _ = RegenerateAsync(false); - done.Click += (_, _) => flyout.Hide(); - flyout.Closed += (_, _) => target.Focus(FocusState.Programmatic); - flyout.ShowAt(anchor); - } - - private async void TotpSetupButton_Click(object sender, RoutedEventArgs e) - { - if (_currentFull is null) - { - return; - } - EntryFullDto current = _currentFull; - TotpConfigDto? existing = current.Totp; - var secret = new TextBox - { - Header = "Base32 secret", - Text = existing?.SecretBase32 ?? string.Empty, - FontFamily = new FontFamily("Consolas"), - }; - var algorithm = new ComboBox - { - Header = "Algorithm", - ItemsSource = new[] { "SHA1", "SHA256", "SHA512" }, - SelectedItem = existing?.Algorithm ?? "SHA1", - }; - var digits = new ComboBox - { - Header = "Digits", - ItemsSource = new[] { "6", "8" }, - SelectedItem = (existing?.Digits ?? 6).ToString(), - }; - var period = new NumberBox - { - Header = "Period (seconds)", - Value = existing?.Period ?? 30, - Minimum = 1, - Maximum = 300, - }; - var importStatus = new TextBlock - { - FontSize = 11, - TextWrapping = TextWrapping.Wrap, - Foreground = (Brush)Application.Current.Resources["TextFillColorSecondaryBrush"], - }; - var importFile = new Button { Content = "Import QR image…" }; - var importClipboard = new Button { Content = "Paste QR / otpauth…" }; - var importRow = new StackPanel - { - Orientation = Orientation.Horizontal, - Spacing = 8, - }; - importRow.Children.Add(importFile); - importRow.Children.Add(importClipboard); - async Task ApplyImportedUriAsync(string? uri) - { - if (string.IsNullOrWhiteSpace(uri) || - !uri.StartsWith("otpauth://", StringComparison.OrdinalIgnoreCase)) - { - importStatus.Text = "No otpauth QR code found. Paste a Base32 secret instead."; - return; - } - try - { - TotpConfigDto parsed = await _core.ParseTotpUriAsync(uri); - secret.Text = parsed.SecretBase32; - algorithm.SelectedItem = parsed.Algorithm; - digits.SelectedItem = parsed.Digits.ToString(); - period.Value = Math.Clamp(parsed.Period, 1, 300); - string account = string.Join(" / ", - new[] { parsed.Issuer, parsed.Account }.Where(value => - !string.IsNullOrWhiteSpace(value))); - importStatus.Text = account.Length == 0 - ? "QR imported. Review the parameters and save." - : $"Imported {account}. Review and save."; - } - catch (Exception ex) - { - importStatus.Text = $"Could not read otpauth URI: {ex.Message}"; - } - } - importFile.Click += async (_, _) => - { - try - { - var picker = new FileOpenPicker - { - SuggestedStartLocation = PickerLocationId.PicturesLibrary, - }; - foreach (string extension in new[] - { - ".png", ".jpg", ".jpeg", ".bmp", ".gif", ".tif", ".tiff", - }) - { - picker.FileTypeFilter.Add(extension); - } - WinRT.Interop.InitializeWithWindow.Initialize(picker, - WinRT.Interop.WindowNative.GetWindowHandle(this)); - StorageFile? file = await picker.PickSingleFileAsync(); - if (file is not null) - { - await ApplyImportedUriAsync(await QrDecoder.DecodeFileAsync(file)); - } - } - catch (Exception ex) - { - importStatus.Text = $"QR image failed: {ex.Message}"; - } - }; - importClipboard.Click += async (_, _) => - { - try - { - await ApplyImportedUriAsync(await QrDecoder.DecodeClipboardAsync()); - } - catch (Exception ex) - { - importStatus.Text = $"Clipboard QR failed: {ex.Message}"; - } - }; - var content = new StackPanel { Spacing = 10 }; - content.Children.Add(importRow); - content.Children.Add(importStatus); - content.Children.Add(secret); - content.Children.Add(algorithm); - content.Children.Add(digits); - content.Children.Add(period); - RightPanelResult result = await ShowDetailPanelAsync( - existing is null ? "Set up TOTP" : "Edit TOTP", - content, - "Save", - existing is null ? null : "Remove"); - if (result == RightPanelResult.Secondary) - { - try - { - await _core.TotpDeleteAsync(current.Uuid); - await SaveAsync(); - await ReloadVaultAsync(current.Uuid); - ShowToast("TOTP removed", InfoBarSeverity.Informational); - } - catch (Exception ex) - { - ShowToast(ex.Message, InfoBarSeverity.Error); - } - return; - } - if (result != RightPanelResult.Primary) - { - return; - } - try - { - await _core.TotpSetAsync(current.Uuid, new TotpConfigDto - { - SecretBase32 = secret.Text.Trim(), - Algorithm = algorithm.SelectedItem as string ?? "SHA1", - Digits = int.TryParse(digits.SelectedItem as string, out int parsedDigits) - ? parsedDigits - : 6, - Period = (int)Math.Clamp(period.Value, 1, 300), - Encoder = "totp", - }); - await SaveAsync(); - await ReloadVaultAsync(current.Uuid); - ShowToast("TOTP saved", InfoBarSeverity.Success); - } - catch (Exception ex) - { - ShowToast(ex.Message, InfoBarSeverity.Error); - } - } - - // ------------------------------------------------------------ save/lock - - private async Task SaveAsync(bool silent = false, bool syncAfterSave = true) - { - if (_dbPath is null) - { - return; - } - try - { - await _core.SaveAsync(_dbPath, Settings.BackupRetention); - MarkLocalDirty(); - if (!silent) - { - ShowToast("Saved", InfoBarSeverity.Success); - } - if (syncAfterSave && Settings.SyncOnSave && IsSyncConfigured) - { - _ = SyncAsync(); - } - } - catch (Exception ex) - { - ShowToast($"Save failed: {ex.Message}", InfoBarSeverity.Error); - throw; - } - } - - private async void LockButton_Click(object sender, RoutedEventArgs e) - => await LockVaultAsync(); - - private async Task LockVaultAsync() - { - if (_busy) - { - return; - } - ClosePanels(); - _busy = true; - try - { - if (_core.IsOpen) - { - // Every edit path saves the database immediately. Saving again - // here would re-encrypt the working copy and mark it dirty even - // when nothing changed, so the next WebDAV open would report - // unsynced local changes and force an unnecessary merge. - await _core.LockAsync(); - } - } - catch (Exception ex) - { - ShowToast($"Lock failed: {ex.Message}", InfoBarSeverity.Error); - _busy = false; - return; - } - _autoLockTimer.Stop(); - _totpTimer.Stop(); - AppLog.Info("vault locked"); - Announce("Vault locked"); - _currentFull = null; - _currentSummary = null; - ResetTotpDisplayState(); - Entries.Clear(); - Groups.Clear(); - NavView.MenuItems.Clear(); - ClearDetail(); - MainRoot.Visibility = Visibility.Collapsed; - UnlockRoot.Visibility = Visibility.Visible; - SearchBox.Visibility = Visibility.Collapsed; - HamburgerButton.Visibility = Visibility.Collapsed; - SearchBox.Text = string.Empty; - MasterPassword.Password = string.Empty; - _masterPassword = null; - SetSyncStatus(IsSyncConfigured ? "Not synced" : "Local only"); - UnlockError.IsOpen = false; - UnlockError.Severity = InfoBarSeverity.Error; - HideUnlockFailureActions(); - UpdateDatabasePath(); - _trayIcon?.SetVaultState(false, null); - _busy = false; - MasterPassword.Focus(FocusState.Programmatic); - } - - private async void SettingsButton_Click(object sender, RoutedEventArgs e) - { - if (_rightPanelOpen) - { - return; - } - // Clear the group highlight while Settings is open. Selecting the - // footer item directly is not supported by NavigationView and can - // destabilize its selection loop. - SelectNavItem(null); - SetSettingsHighlight(true); - var theme = new RadioButtons - { - Header = "Appearance", - Items = - { - "Use system setting", - "Light", - "Dark", - }, - SelectedIndex = Settings.Theme switch - { - "Light" => 1, - "Dark" => 2, - _ => 0, - }, - }; - var clipboard = new ToggleSwitch - { - Header = "Clear copied secrets after 30 seconds", - OnContent = "On", - OffContent = "Off", - IsOn = Settings.ClearClipboardAfter30Seconds, - }; - var autoLock = new ToggleSwitch - { - Header = "Lock the vault after inactivity", - OnContent = "On", - OffContent = "Off", - IsOn = Settings.AutoLockEnabled, - }; - var startMinimized = new ToggleSwitch - { - Header = "Start minimized to the notification area", - OnContent = "On", - OffContent = "Off", - IsOn = Settings.StartMinimized, - }; - var minutes = new NumberBox - { - Header = "Inactivity minutes before lock", - Value = Settings.AutoLockMinutes, - Minimum = 1, - Maximum = 240, - SpinButtonPlacementMode = NumberBoxSpinButtonPlacementMode.Inline, - }; - var retention = new NumberBox - { - Header = "Backup copies to keep", - Value = Settings.BackupRetention, - Minimum = 1, - Maximum = 200, - SpinButtonPlacementMode = NumberBoxSpinButtonPlacementMode.Inline, - }; - var webdavUrl = new TextBox - { - Header = "WebDAV file URL", - Text = Settings.WebDavUrl ?? string.Empty, - PlaceholderText = "https://dav.example.com/keepassity.kdbx", - IsReadOnly = _webDavSource, - }; - var webdavUser = new TextBox - { - Header = "WebDAV username", - Text = Settings.WebDavUsername ?? string.Empty, - IsReadOnly = _webDavSource, - }; - var webdavPassword = new PasswordBox - { - Header = "WebDAV password (leave blank to keep the stored one)", - PasswordRevealMode = PasswordRevealMode.Peek, - }; - var storedPasswordText = new TextBlock - { - FontSize = 11, - TextWrapping = TextWrapping.Wrap, - Foreground = (Brush)Application.Current.Resources["TextFillColorSecondaryBrush"], - }; - var clearStoredPassword = new Button - { - Content = "Clear stored password", - HorizontalAlignment = HorizontalAlignment.Left, - IsEnabled = false, - }; - var storedPasswordRow = new StackPanel { Spacing = 6 }; - storedPasswordRow.Children.Add(storedPasswordText); - storedPasswordRow.Children.Add(clearStoredPassword); - void RefreshStoredCredentialState() - { - string currentUrl = webdavUrl.Text.Trim(); - string currentUser = webdavUser.Text.Trim(); - bool stored = currentUrl.Length > 0 && currentUser.Length > 0 && - _credentials.HasPassword(currentUrl, currentUser); - storedPasswordText.Text = stored - ? $"Password stored for {currentUser} (Windows DPAPI)." - : "No stored password for this WebDAV target."; - clearStoredPassword.IsEnabled = stored; - } - webdavUrl.TextChanged += (_, _) => RefreshStoredCredentialState(); - webdavUser.TextChanged += (_, _) => RefreshStoredCredentialState(); - clearStoredPassword.Click += (_, _) => - { - string currentUrl = webdavUrl.Text.Trim(); - string currentUser = webdavUser.Text.Trim(); - if (currentUrl.Length == 0 || currentUser.Length == 0) - { - return; - } - // Deletes the DPAPI entry only; the remote database and settings are - // untouched. No secret is ever shown or logged here. - if (_credentials.DeletePassword(currentUrl, currentUser)) - { - AppLog.Info("stored WebDAV credential cleared"); - ShowToast("Stored WebDAV password cleared", InfoBarSeverity.Success); - } - else - { - ShowToast("No stored password to clear.", InfoBarSeverity.Informational); - } - RefreshStoredCredentialState(); - }; - RefreshStoredCredentialState(); - var syncOnSave = new ToggleSwitch - { - Header = "Sync after saving changes", - OnContent = "On", - OffContent = "Off", - IsOn = Settings.SyncOnSave, - }; - theme.SelectionChanged += (_, _) => - { - Settings.Theme = theme.SelectedIndex switch - { - 1 => "Light", - 2 => "Dark", - _ => "System", - }; - ApplyThemePreference(Settings.Theme); - _settingsStore.Save(); - }; - clipboard.Toggled += (_, _) => - { - Settings.ClearClipboardAfter30Seconds = clipboard.IsOn; - _settingsStore.Save(); - }; - autoLock.Toggled += (_, _) => - { - Settings.AutoLockEnabled = autoLock.IsOn; - _settingsStore.Save(); - }; - startMinimized.Toggled += (_, _) => - { - Settings.StartMinimized = startMinimized.IsOn; - _settingsStore.Save(); - }; - minutes.ValueChanged += (_, _) => - { - if (!double.IsNaN(minutes.Value)) - { - Settings.AutoLockMinutes = Math.Clamp((int)minutes.Value, 1, 240); - _settingsStore.Save(); - } - }; - retention.ValueChanged += (_, _) => - { - if (!double.IsNaN(retention.Value)) - { - Settings.BackupRetention = Math.Clamp((int)retention.Value, 1, 200); - _settingsStore.Save(); - } - }; - syncOnSave.Toggled += (_, _) => - { - Settings.SyncOnSave = syncOnSave.IsOn; - _settingsStore.Save(); - }; - var content = new StackPanel { Spacing = 14 }; - content.Children.Add(theme); - content.Children.Add(clipboard); - content.Children.Add(autoLock); - content.Children.Add(startMinimized); - content.Children.Add(minutes); - content.Children.Add(retention); - content.Children.Add(new TextBlock - { - Text = "WebDAV", - FontWeight = Microsoft.UI.Text.FontWeights.SemiBold, - Margin = new Thickness(0, 8, 0, 0), - }); - content.Children.Add(webdavUrl); - content.Children.Add(webdavUser); - content.Children.Add(webdavPassword); - content.Children.Add(new TextBlock - { - Text = "Nextcloud/ownCloud with two-factor authentication requires an app " + - "password. Server URL presets are offered when opening a database from " + - "WebDAV.", - FontSize = 11, - TextWrapping = TextWrapping.Wrap, - Foreground = (Brush)Application.Current.Resources["TextFillColorTertiaryBrush"], - }); - content.Children.Add(storedPasswordRow); - content.Children.Add(syncOnSave); - content.Children.Add(new TextBlock - { - Text = _webDavSource - ? "This database was opened from WebDAV; the source URL is fixed for this " + - "session. To switch sources, lock and use Open from WebDAV… on the unlock " + - "page. The WebDAV password is stored with Windows DPAPI; clearing it does " + - "not touch the remote database." - : "The URL must point to the .kdbx file. The WebDAV password is stored " + - "with Windows DPAPI, not in the plain settings file; clearing it does " + - "not touch the remote database.", - FontSize = 11, - TextWrapping = TextWrapping.Wrap, - Foreground = (Brush)Application.Current.Resources["TextFillColorTertiaryBrush"], - }); - string appVersion = typeof(MainWindow).Assembly - .GetCustomAttribute()?.InformationalVersion - ?? typeof(MainWindow).Assembly.GetName().Version?.ToString(3) - ?? "unknown"; - // Deterministic builds append "+" to the informational - // version; the About page shows the human-facing version only. - int versionMetadata = appVersion.IndexOf('+'); - if (versionMetadata > 0) - { - appVersion = appVersion[..versionMetadata]; - } - var aboutIcon = new Image - { - Width = 72, - Height = 72, - HorizontalAlignment = HorizontalAlignment.Left, - Margin = new Thickness(0, 8, 0, 0), - Visibility = Visibility.Collapsed, - }; - // The preview loads asynchronously from the assets copied next to the - // executable; the section stays without a logo if the asset is missing. - _ = ApplyAboutIconAsync(aboutIcon); - content.Children.Add(aboutIcon); - content.Children.Add(new TextBlock - { - Text = "About", - FontWeight = Microsoft.UI.Text.FontWeights.SemiBold, - Margin = new Thickness(0, 8, 0, 0), - }); - content.Children.Add(new TextBlock - { - Text = $"keepassity {appVersion} · local-first KeePass-compatible client", - FontSize = 11, - TextWrapping = TextWrapping.Wrap, - Foreground = (Brush)Application.Current.Resources["TextFillColorTertiaryBrush"], - }); - // GPL notice (M3-10): version plus the GPL-3.0-or-later short notice and - // links to the license text and public source, as the license requires. - content.Children.Add(new TextBlock - { - Text = "License: GNU General Public License, version 3 or later " + - "(GPL-3.0-or-later).", - FontSize = 11, - FontWeight = Microsoft.UI.Text.FontWeights.SemiBold, - TextWrapping = TextWrapping.Wrap, - }); - content.Children.Add(new TextBlock - { - Text = "This program is free software: you can redistribute it and/or modify it " + - "under the terms of the GNU General Public License as published by the Free " + - "Software Foundation, either version 3 of the License, or (at your option) " + - "any later version. This program is distributed in the hope that it will be " + - "useful, but WITHOUT ANY WARRANTY; without even the implied warranty of " + - "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General " + - "Public License for more details; the full license text ships in the " + - "LICENSE file of the source repository.", - FontSize = 10, - TextWrapping = TextWrapping.Wrap, - Foreground = (Brush)Application.Current.Resources["TextFillColorTertiaryBrush"], - }); - var licenseLinks = new StackPanel - { - Orientation = Orientation.Horizontal, - Spacing = 12, - }; - licenseLinks.Children.Add(new HyperlinkButton - { - Content = "GPL-3.0 license text", - NavigateUri = new Uri("https://www.gnu.org/licenses/gpl-3.0.html"), - Padding = new Thickness(0), - FontSize = 11, - }); - licenseLinks.Children.Add(new HyperlinkButton - { - Content = "Source code", - NavigateUri = new Uri("https://github.com/simplenty/keepassity"), - Padding = new Thickness(0), - FontSize = 11, - }); - content.Children.Add(licenseLinks); - var diagnostics = new Button - { - Content = "Export diagnostics…", - HorizontalAlignment = HorizontalAlignment.Left, - }; - diagnostics.Click += async (_, _) => - { - try - { - string path = await DiagnosticsService.ExportAsync(Settings); - ShowToast($"Diagnostics exported: {path}", InfoBarSeverity.Success); - } - catch (Exception ex) - { - AppLog.Error("diagnostics export failed", ex); - ShowToast($"Diagnostics export failed: {ex.Message}", InfoBarSeverity.Error); - } - }; - content.Children.Add(diagnostics); - RightPanelResult settingsResult = - await ShowRightPanelAsync("Settings", content, "Save", closeText: "Cancel"); - SetSettingsHighlight(false); - if (ReferenceEquals(NavView.SelectedItem, null)) - { - RestoreGroupNavSelection(); - } - if (settingsResult != RightPanelResult.Primary) - { - return; - } - string url = webdavUrl.Text.Trim(); - if (url.Length > 0 && - (!Uri.TryCreate(url, UriKind.Absolute, out Uri? parsed) || - parsed.Scheme != Uri.UriSchemeHttps)) - { - ShowToast("WebDAV URLs must use https:// (the password is sent with " + - "Basic authentication, which requires TLS).", - InfoBarSeverity.Error); - return; - } - string username = webdavUser.Text.Trim(); - Settings.WebDavUrl = url.Length == 0 ? null : url; - Settings.WebDavUsername = username.Length == 0 ? null : username; - try - { - if (webdavPassword.Password.Length > 0) - { - if (string.IsNullOrEmpty(Settings.WebDavUrl) || - string.IsNullOrEmpty(Settings.WebDavUsername)) - { - ShowToast("Enter the WebDAV URL and username before the password.", - InfoBarSeverity.Warning); - return; - } - _credentials.SavePassword(Settings.WebDavUrl, Settings.WebDavUsername, - webdavPassword.Password); - } - _settingsStore.Save(); - } - catch (Exception ex) - { - ShowToast($"Cannot store WebDAV credential: {ex.Message}", InfoBarSeverity.Error); - return; - } - SetSyncStatus(IsSyncConfigured ? "Not synced" : "Local only"); - if (IsSyncConfigured) - { - ShowToast("WebDAV settings saved. Syncing…", InfoBarSeverity.Informational); - _ = SyncAsync(startup: true); - } - } - - // ------------------------------------------------------- right-side panel - - private static StackPanel CreateIconLabel(string text, string glyph) - { - var panel = new StackPanel - { - Orientation = Orientation.Horizontal, - Spacing = 6, - }; - panel.Children.Add(new FontIcon { Glyph = glyph, FontSize = 12 }); - panel.Children.Add(new TextBlock - { - Text = text, - FontSize = 12, - VerticalAlignment = VerticalAlignment.Center, - }); - return panel; - } - - private Button CreateToolbarButton(string text, string glyph) - { - var button = new Button - { - Content = CreateIconLabel(text, glyph), - Style = (Style)Root.Resources["ToolbarButton"], - }; - // Dynamic buttons carry no accessible name from an icon-only label; - // derive it from the visible text. - AutomationProperties.SetName(button, text); - return button; - } - - private static Button CreateActionButton(string text, string glyph, bool accent) - { - var button = new Button { Content = CreateIconLabel(text, glyph) }; - if (accent) - { - button.Style = (Style)Application.Current.Resources["AccentButtonStyle"]; - } - AutomationProperties.SetName(button, text); - return button; - } - - private void RightPanel_KeyDown(object sender, KeyRoutedEventArgs e) - { - if (e.Key != VirtualKey.Escape) - { - return; - } - if (_rightPanelOpen) - { - CloseRightPanel(); - e.Handled = true; - } - else if (_detailPanelOpen) - { - CloseDetailPanel(); - e.Handled = true; - } - } - - private void EnsureRightPanel() - { - if (_rightPanel is not null) - { - return; - } - _rightPanel = new Grid { Visibility = Visibility.Collapsed }; - AutomationProperties.SetAutomationId(_rightPanel, "RightPanel"); - _rightPanel.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); - _rightPanel.RowDefinitions.Add( - new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }); - _rightPanel.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); - - var header = new Grid { Padding = new Thickness(32, 22, 32, 18) }; - _rightPanelTitle = new TextBlock - { - FontSize = 22, - FontWeight = Microsoft.UI.Text.FontWeights.SemiBold, - VerticalAlignment = VerticalAlignment.Center, - TextTrimming = TextTrimming.CharacterEllipsis, - }; - AutomationProperties.SetAutomationId(_rightPanelTitle, "RightPanelTitle"); - header.Children.Add(_rightPanelTitle); - _rightPanel.Children.Add(header); - - _rightPanelContent = new ContentControl - { - HorizontalContentAlignment = HorizontalAlignment.Stretch, - Margin = new Thickness(32, 0, 32, 0), - }; - var scroll = new ScrollViewer - { - Content = _rightPanelContent, - VerticalScrollBarVisibility = ScrollBarVisibility.Auto, - Padding = new Thickness(0, 0, 8, 0), - }; - Grid.SetRow(scroll, 1); - _rightPanel.Children.Add(scroll); - - _rightPanelActions = new StackPanel - { - Orientation = Orientation.Horizontal, - HorizontalAlignment = HorizontalAlignment.Right, - Spacing = 8, - Padding = new Thickness(32, 16, 32, 24), - }; - Grid.SetRow(_rightPanelActions, 2); - _rightPanel.Children.Add(_rightPanelActions); - WorkspacePanel.Children.Add(_rightPanel); - } - - private void SetRightPanelUnderlyingVisible(bool visible) - { - foreach (UIElement child in WorkspacePanel.Children) - { - if (!ReferenceEquals(child, _rightPanel)) - { - child.Visibility = visible ? Visibility.Visible : Visibility.Collapsed; - } - } - } - - private void SetDetailPanelUnderlyingVisible(bool visible) - { - foreach (UIElement child in DetailPane.Children) - { - if (!ReferenceEquals(child, _detailPanel)) - { - child.Visibility = visible ? Visibility.Visible : Visibility.Collapsed; - } - } - } - - private async Task ShowRightPanelAsync(string title, UIElement content, - string primaryText, string? secondaryText = null, string? closeText = "Cancel", - string primaryGlyph = "\uE74E") - { - if (_rightPanelOpen) - { - return RightPanelResult.Close; - } - CloseDetailPanel(); - EnsureRightPanel(); - _rightPanelOpen = true; - _rightPanelTitle!.Text = title; - AutomationProperties.SetName(_rightPanel, $"{title} panel"); - _rightPanelContent!.Content = content; - _rightPanelActions!.Children.Clear(); - var completion = new TaskCompletionSource( - TaskCreationOptions.RunContinuationsAsynchronously); - _rightPanelCompletion = completion; - void Finish(RightPanelResult result) => completion.TrySetResult(result); - - if (!string.IsNullOrWhiteSpace(closeText)) - { - var close = CreateActionButton(closeText, "\uE711", accent: false); - close.Click += (_, _) => Finish(RightPanelResult.Close); - _rightPanelActions.Children.Add(close); - } - if (!string.IsNullOrWhiteSpace(secondaryText)) - { - var secondary = CreateActionButton(secondaryText, "\uE74D", accent: false); - secondary.Click += (_, _) => Finish(RightPanelResult.Secondary); - _rightPanelActions.Children.Add(secondary); - } - var primary = CreateActionButton(primaryText, primaryGlyph, accent: true); - primary.Click += (_, _) => Finish(RightPanelResult.Primary); - _rightPanelActions.Children.Add(primary); - - SetRightPanelUnderlyingVisible(false); - _rightPanel!.Visibility = Visibility.Visible; - AnimatePanelIn(_rightPanel); - RightPanelResult result = await completion.Task; - await AnimatePanelOutAsync(_rightPanel); - SetRightPanelUnderlyingVisible(true); - _rightPanelContent.Content = null; - _rightPanelActions.Children.Clear(); - _rightPanelOpen = false; - _rightPanelCompletion = null; - return result; - } - - private void CloseRightPanel() - { - if (_rightPanelOpen) - { - _rightPanelCompletion?.TrySetResult(RightPanelResult.Close); - } - } - - private void EnsureDetailPanel() - { - if (_detailPanel is not null) - { - return; - } - _detailPanel = new Grid - { - Visibility = Visibility.Collapsed, - Margin = new Thickness(-32, -22, -32, -24), - }; - AutomationProperties.SetAutomationId(_detailPanel, "DetailDialog"); - _detailPanel.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); - _detailPanel.RowDefinitions.Add( - new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }); - _detailPanel.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); - - var header = new Grid { Padding = new Thickness(32, 22, 32, 18) }; - header.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - header.ColumnDefinitions.Add( - new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - var back = CreateToolbarButton("Back", "\uE72B"); - back.Click += (_, _) => CloseDetailPanel(); - header.Children.Add(back); - _detailPanelTitle = new TextBlock - { - FontSize = 22, - FontWeight = Microsoft.UI.Text.FontWeights.SemiBold, - VerticalAlignment = VerticalAlignment.Center, - Margin = new Thickness(16, 0, 0, 0), - TextTrimming = TextTrimming.CharacterEllipsis, - }; - AutomationProperties.SetAutomationId(_detailPanelTitle, "DetailDialogTitle"); - Grid.SetColumn(_detailPanelTitle, 1); - header.Children.Add(_detailPanelTitle); - _detailPanel.Children.Add(header); - - _detailPanelContent = new ContentControl - { - HorizontalContentAlignment = HorizontalAlignment.Stretch, - Margin = new Thickness(32, 0, 32, 0), - }; - var scroll = new ScrollViewer - { - Content = _detailPanelContent, - VerticalScrollBarVisibility = ScrollBarVisibility.Auto, - Padding = new Thickness(0, 0, 8, 0), - }; - Grid.SetRow(scroll, 1); - _detailPanel.Children.Add(scroll); - - _detailPanelActions = new StackPanel - { - Orientation = Orientation.Horizontal, - HorizontalAlignment = HorizontalAlignment.Right, - Spacing = 8, - Padding = new Thickness(32, 16, 32, 24), - }; - Grid.SetRow(_detailPanelActions, 2); - _detailPanel.Children.Add(_detailPanelActions); - Grid.SetRow(_detailPanel, 0); - Grid.SetRowSpan(_detailPanel, 2); - DetailPane.Children.Add(_detailPanel); - } - - private async Task ShowDetailPanelAsync(string title, UIElement content, - string primaryText, string? secondaryText = null, string? closeText = "Cancel", - string primaryGlyph = "\uE74E") - { - if (_detailPanelOpen) - { - return RightPanelResult.Close; - } - CloseRightPanel(); - EnsureDetailPanel(); - _detailPanelOpen = true; - _detailPanelTitle!.Text = title; - AutomationProperties.SetName(_detailPanel, $"{title} dialog"); - _detailPanelContent!.Content = content; - _detailPanelActions!.Children.Clear(); - var completion = new TaskCompletionSource( - TaskCreationOptions.RunContinuationsAsynchronously); - _detailPanelCompletion = completion; - void Finish(RightPanelResult result) => completion.TrySetResult(result); - - if (!string.IsNullOrWhiteSpace(closeText)) - { - var close = CreateActionButton(closeText, "\uE711", accent: false); - close.Click += (_, _) => Finish(RightPanelResult.Close); - _detailPanelActions.Children.Add(close); - } - if (!string.IsNullOrWhiteSpace(secondaryText)) - { - var secondary = CreateActionButton(secondaryText, "\uE74D", accent: false); - secondary.Click += (_, _) => Finish(RightPanelResult.Secondary); - _detailPanelActions.Children.Add(secondary); - } - var primary = CreateActionButton(primaryText, primaryGlyph, accent: true); - primary.Click += (_, _) => Finish(RightPanelResult.Primary); - _detailPanelActions.Children.Add(primary); - - SetDetailPanelUnderlyingVisible(false); - _detailPanel!.Visibility = Visibility.Visible; - AnimatePanelIn(_detailPanel); - RightPanelResult result = await completion.Task; - await AnimatePanelOutAsync(_detailPanel); - SetDetailPanelUnderlyingVisible(true); - _detailPanelContent.Content = null; - _detailPanelActions.Children.Clear(); - _detailPanelOpen = false; - _detailPanelCompletion = null; - return result; - } - - private void CloseDetailPanel() - { - if (_detailPanelOpen) - { - _detailPanelCompletion?.TrySetResult(RightPanelResult.Close); - } - } - - private void ClosePanels() - { - CloseRightPanel(); - CloseDetailPanel(); - } - - private void ShowToast(string message, InfoBarSeverity severity) - { - Toast.Message = message; - Toast.Severity = severity; - Toast.IsOpen = true; - _toastTimer.Stop(); - _toastTimer.Start(); - Announce(message); - } -} - -public sealed class GroupItem -{ - public GroupItem(string? uuid, string name, int count, string glyph) - { - Uuid = uuid; - Name = name; - Count = count.ToString(); - Glyph = glyph; - } - - public string? Uuid { get; } - public string Name { get; } - public string Count { get; } - public string Glyph { get; } - public int CountValue => int.TryParse(Count, out int value) ? value : 0; -} - -public sealed class EntryItem : INotifyPropertyChanged -{ - private static readonly Color[] Palette = - { - Color.FromArgb(255, 0, 120, 212), - Color.FromArgb(255, 135, 100, 184), - Color.FromArgb(255, 16, 124, 16), - Color.FromArgb(255, 202, 80, 16), - Color.FromArgb(255, 0, 153, 188), - Color.FromArgb(255, 197, 15, 31), - }; - - private string _groupUuid; - private string _groupName; - private string _secondary; - - public EntryItem(EntrySummaryDto entry, string groupName) - { - Uuid = entry.Uuid; - _groupUuid = entry.GroupUuid; - Title = entry.Title; - Username = entry.Username; - Url = entry.Url; - _groupName = groupName; - HasTotp = entry.HasTotp; - _secondary = SecondaryFor(entry.Username, entry.Url, groupName); - Initial = entry.Title.Length > 0 ? entry.Title[..1].ToUpperInvariant() : "?"; - int hash = 0; - foreach (char character in entry.Uuid) - { - hash = unchecked((hash * 31) + character); - } - AvatarBrush = new SolidColorBrush(Palette[(hash & int.MaxValue) % Palette.Length]); - } - - public event PropertyChangedEventHandler? PropertyChanged; - - public string Uuid { get; } - public string GroupUuid => _groupUuid; - public string Title { get; } - public string Username { get; } - public string Url { get; } - public string GroupName => _groupName; - public string Secondary => _secondary; - public bool HasTotp { get; } - public string Initial { get; } - public Brush AvatarBrush { get; } - public Visibility TotpVisibility => HasTotp ? Visibility.Visible : Visibility.Collapsed; - - /// - /// Updates the group shown for an entry that stays visible after a move (All - /// entries / search view). Mutating the existing item keeps the ListView's - /// selection and scroll position instead of rebuilding the middle column. - /// - public void UpdateGroup(string groupUuid, string groupName) - { - if (_groupUuid == groupUuid && _groupName == groupName) - { - return; - } - _groupUuid = groupUuid; - _groupName = groupName; - _secondary = SecondaryFor(Username, Url, groupName); - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(GroupUuid))); - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(GroupName))); - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Secondary))); - } - - private static string SecondaryFor(string username, string url, string groupName) - => !string.IsNullOrWhiteSpace(username) - ? username - : Uri.TryCreate(url, UriKind.Absolute, out Uri? uri) && - !string.IsNullOrWhiteSpace(uri.Host) - ? uri.Host - : groupName; -} diff --git a/apps/windows/Keepassity.Mock/SingleInstanceRelay.cs b/apps/windows/Keepassity.Mock/SingleInstanceRelay.cs deleted file mode 100644 index 3defe06..0000000 --- a/apps/windows/Keepassity.Mock/SingleInstanceRelay.cs +++ /dev/null @@ -1,447 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-or-later -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Security.Cryptography; -using System.Text; - -namespace Keepassity.Mock; - -/// -/// Minimal cross-process hand-off for "open this .kdbx" requests, used when a -/// second keepassity launch (Explorer double-click / "Open with") should switch -/// the already-running instance instead of doing nothing. -/// -/// The running instance owns a tiny hidden top-level window whose title is -/// derived from the executable path; the second instance finds it with -/// FindWindow, verifies the owning process is the same application, and sends -/// the database path with WM_COPYDATA. The receiver validates the payload -/// (signature, size, sender process, existing .kdbx path) before handing the -/// path to the UI. This is the classic Win32 single-instance pattern and needs -/// no new dependency; an in-place activation (AppInstance redirection) would -/// require restructuring the app's launch path and is deliberately not used. -/// -internal sealed class SingleInstanceRelay : IDisposable -{ - private const int WmCopyData = 0x004A; - private const int GwlWndProc = -4; - private const uint Magic = 0x4B504458; // 'KPDX' - private const uint WsPopup = 0x80000000; - private const uint WsExToolWindow = 0x00000080; - private const uint SmtoBlock = 0x0001; - private const uint SmtoAbortIfHung = 0x0002; - private const uint SendTimeoutMilliseconds = 2000; - - /// Generous upper bound for a Windows path in UTF-16 bytes. - internal const int MaxPayloadBytes = 64 * 1024; - - /// Maximum path length Windows itself accepts (32767 characters). - internal const int MaxPathCharacters = 32767; - - private static readonly Lazy LazyRelayWindowTitle = new(() => - { - string executable = Environment.ProcessPath ?? "keepassity"; - byte[] hash = SHA256.HashData( - Encoding.UTF8.GetBytes(executable.ToLowerInvariant())); - // Deliberately does not contain "keepassity": the helper windows must not - // be mistaken for the main window by the activation fallback. - return "kdbx-open-relay-" + Convert.ToHexString(hash)[..16].ToLowerInvariant(); - }); - - private readonly Action _onDatabasePath; - // The window procedure holds a raw pointer to this delegate; keep it rooted. - private readonly SubclassProc _windowProc; - private IntPtr _window; - private IntPtr _previousProc; - private bool _disposed; - - [UnmanagedFunctionPointer(CallingConvention.Winapi)] - private delegate IntPtr SubclassProc(IntPtr hWnd, uint message, IntPtr wParam, - IntPtr lParam); - - [StructLayout(LayoutKind.Sequential)] - private struct CopyDataStruct - { - public IntPtr Signature; - public int Size; - public IntPtr Data; - } - - private SingleInstanceRelay(Action onDatabasePath) - { - _onDatabasePath = onDatabasePath; - _windowProc = WindowProc; - } - - /// Window title the receiving instance registers for discovery. - internal static string RelayWindowTitle => LazyRelayWindowTitle.Value; - - /// - /// Creates the hidden relay window for this process. Returns null (and logs) - /// when the window cannot be created; the app keeps working without IPC. - /// - public static SingleInstanceRelay? TryStart(Action onDatabasePath) - { - var relay = new SingleInstanceRelay(onDatabasePath); - bool created = false; - try - { - created = relay.CreateWindow(); - if (created) - { - AppLog.Info("single-instance relay window ready"); - return relay; - } - } - catch (Exception ex) - { - AppLog.Error("single-instance relay could not be started", ex); - } - finally - { - // Always release the partially created window, also when logging or - // window creation threw (CodeQL cs/dispose-not-called-on-throw). - if (!created) - { - relay.Dispose(); - } - } - return null; - } - - /// - /// Sends an open request to the running instance for the same executable. - /// Returns true only when the request was delivered and accepted. - /// - internal static bool TryForward(string databasePath, out string outcome) - { - outcome = "not sent"; - if (!TryNormalizeDatabasePath(databasePath, out string fullPath)) - { - outcome = "the database path is invalid"; - return false; - } - IntPtr target = FindWindow(null, RelayWindowTitle); - if (target == IntPtr.Zero) - { - outcome = "no running instance answered"; - return false; - } - _ = GetWindowThreadProcessId(target, out uint targetProcessId); - if (targetProcessId == 0 || targetProcessId == (uint)Environment.ProcessId) - { - outcome = "the relay window has an unexpected owner"; - return false; - } - if (!IsSameApplication(targetProcessId)) - { - outcome = "the relay window belongs to another application"; - return false; - } - byte[]? payload = EncodePath(fullPath); - if (payload is null) - { - outcome = "the database path is too long"; - return false; - } - IntPtr buffer = Marshal.AllocHGlobal(payload.Length); - IntPtr senderWindow = IntPtr.Zero; - try - { - Marshal.Copy(payload, 0, buffer, payload.Length); - // WM_COPYDATA expects wParam to identify a window owned by the - // sending process. A hidden STATIC window is enough for that; the - // receiver only uses it to check the sender process. - senderWindow = CreateWindowEx(WsExToolWindow, "STATIC", - "kdbx-open-sender", WsPopup, 0, 0, 0, 0, - IntPtr.Zero, IntPtr.Zero, GetModuleHandle(null), IntPtr.Zero); - if (senderWindow == IntPtr.Zero) - { - outcome = "the sender window could not be created"; - return false; - } - var data = new CopyDataStruct - { - Signature = new IntPtr(Magic), - Size = payload.Length, - Data = buffer, - }; - IntPtr structPointer = Marshal.AllocHGlobal(Marshal.SizeOf()); - try - { - Marshal.StructureToPtr(data, structPointer, false); - IntPtr sent = SendMessageTimeout(target, WmCopyData, senderWindow, - structPointer, SmtoBlock | SmtoAbortIfHung, SendTimeoutMilliseconds, - out IntPtr messageResult); - if (sent == IntPtr.Zero) - { - outcome = $"the receiver did not answer (error {Marshal.GetLastPInvokeError()})"; - return false; - } - if (messageResult == IntPtr.Zero) - { - outcome = "the running instance rejected the request"; - return false; - } - outcome = "the running instance received the path"; - return true; - } - finally - { - Marshal.FreeHGlobal(structPointer); - } - } - finally - { - if (senderWindow != IntPtr.Zero) - { - _ = DestroyWindow(senderWindow); - } - Marshal.FreeHGlobal(buffer); - } - } - - /// Encodes a path as UTF-16LE bytes, or null when it is unusable. - internal static byte[]? EncodePath(string path) - { - if (string.IsNullOrWhiteSpace(path)) - { - return null; - } - string fullPath; - try - { - fullPath = Path.GetFullPath(path); - } - catch - { - return null; - } - if (fullPath.Length > MaxPathCharacters) - { - return null; - } - byte[] payload = Encoding.Unicode.GetBytes(fullPath); - return payload.Length is > 0 and <= MaxPayloadBytes ? payload : null; - } - - /// Decodes a UTF-16LE payload, or null when it is malformed. - internal static string? DecodePath(ReadOnlySpan payload) - { - if (payload.Length == 0 || payload.Length > MaxPayloadBytes || - payload.Length % 2 != 0) - { - return null; - } - string decoded = Encoding.Unicode.GetString(payload); - return decoded.IndexOf('\0') >= 0 ? null : decoded; - } - - /// - /// Validates a candidate path for the open hand-off: absolute path, at most - /// the Windows path limit, an existing .kdbx file. - /// - internal static bool TryNormalizeDatabasePath(string? candidate, out string fullPath) - { - fullPath = string.Empty; - if (string.IsNullOrWhiteSpace(candidate) || - candidate.Length > MaxPathCharacters || - candidate.IndexOf('\0') >= 0) - { - return false; - } - try - { - fullPath = Path.GetFullPath(candidate); - } - catch - { - return false; - } - return fullPath.EndsWith(".kdbx", StringComparison.OrdinalIgnoreCase) && - File.Exists(fullPath); - } - - private bool CreateWindow() - { - _window = CreateWindowEx(WsExToolWindow, "STATIC", RelayWindowTitle, WsPopup, - 0, 0, 0, 0, IntPtr.Zero, IntPtr.Zero, GetModuleHandle(null), IntPtr.Zero); - if (_window == IntPtr.Zero) - { - AppLog.Warn("single-instance relay: hidden window could not be created " + - $"(error {Marshal.GetLastPInvokeError()})"); - return false; - } - Marshal.SetLastPInvokeError(0); - _previousProc = SetWindowLongPtr(_window, GwlWndProc, - Marshal.GetFunctionPointerForDelegate(_windowProc)); - int error = Marshal.GetLastPInvokeError(); - if (_previousProc == IntPtr.Zero && error != 0) - { - AppLog.Warn($"single-instance relay: window procedure hook failed (error {error})"); - _ = DestroyWindow(_window); - _window = IntPtr.Zero; - return false; - } - return true; - } - - private IntPtr WindowProc(IntPtr hWnd, uint message, IntPtr wParam, IntPtr lParam) - { - try - { - if (!_disposed && message == WmCopyData) - { - if (TryReadOpenRequest(wParam, lParam, out string? databasePath) && - databasePath is not null) - { - AppLog.Info("open request received from another instance"); - _onDatabasePath(databasePath); - return new IntPtr(1); - } - return IntPtr.Zero; - } - } - catch (Exception ex) - { - // A throwing window procedure would take down the process. - AppLog.Error("single-instance relay: request handling failed", ex); - } - return CallWindowProc(_previousProc, hWnd, message, wParam, lParam); - } - - private static bool TryReadOpenRequest(IntPtr senderWindow, IntPtr lParam, - out string? databasePath) - { - databasePath = null; - if (senderWindow == IntPtr.Zero || lParam == IntPtr.Zero) - { - Reject("the sender window is missing"); - return false; - } - _ = GetWindowThreadProcessId(senderWindow, out uint senderProcessId); - if (senderProcessId == 0 || senderProcessId == (uint)Environment.ProcessId) - { - Reject("the sender process is invalid"); - return false; - } - if (!IsSameApplication(senderProcessId)) - { - Reject("the sender process is not keepassity"); - return false; - } - CopyDataStruct data = Marshal.PtrToStructure(lParam); - if (data.Signature != new IntPtr(Magic)) - { - Reject("the payload signature is wrong"); - return false; - } - if (data.Data == IntPtr.Zero || data.Size <= 0 || - data.Size > MaxPayloadBytes || data.Size % 2 != 0) - { - Reject("the payload size is invalid"); - return false; - } - byte[] payload = new byte[data.Size]; - Marshal.Copy(data.Data, payload, 0, payload.Length); - string? decoded = DecodePath(payload); - if (decoded is null || - !TryNormalizeDatabasePath(decoded, out string fullPath)) - { - Reject("the payload is not an existing .kdbx path"); - return false; - } - databasePath = fullPath; - return true; - } - - private static void Reject(string reason) - { - AppLog.Warn($"single-instance relay: ignored an open request ({reason})"); - } - - private static bool IsSameApplication(uint processId) - { - string? expectedName = Path.GetFileName(Environment.ProcessPath); - if (string.IsNullOrEmpty(expectedName)) - { - return true; - } - try - { - using Process process = Process.GetProcessById((int)processId); - string actualName = process.ProcessName + ".exe"; - return string.Equals(actualName, expectedName, StringComparison.OrdinalIgnoreCase); - } - catch - { - // The process may have exited or the sandbox may deny the query; the - // payload itself is still validated, so do not drop a valid request. - AppLog.Warn("single-instance relay: sender process name could not be checked"); - return true; - } - } - - private static IntPtr SetWindowLongPtr(IntPtr window, int index, IntPtr value) - => IntPtr.Size == 8 - ? SetWindowLongPtr64(window, index, value) - : new IntPtr(SetWindowLong32(window, index, value.ToInt32())); - - public void Dispose() - { - if (_disposed) - { - return; - } - _disposed = true; - try - { - if (_window != IntPtr.Zero) - { - if (_previousProc != IntPtr.Zero) - { - _ = SetWindowLongPtr(_window, GwlWndProc, _previousProc); - _previousProc = IntPtr.Zero; - } - _ = DestroyWindow(_window); - _window = IntPtr.Zero; - AppLog.Info("single-instance relay window closed"); - } - } - catch (Exception ex) - { - AppLog.Error("single-instance relay cleanup failed", ex); - } - } - - [DllImport("user32.dll", EntryPoint = "SetWindowLongPtrW", SetLastError = true)] - private static extern IntPtr SetWindowLongPtr64(IntPtr window, int index, IntPtr value); - - [DllImport("user32.dll", EntryPoint = "SetWindowLongW", SetLastError = true)] - private static extern int SetWindowLong32(IntPtr window, int index, int value); - - [DllImport("user32.dll", SetLastError = true)] - private static extern IntPtr CallWindowProc(IntPtr previousProc, IntPtr window, - uint message, IntPtr wParam, IntPtr lParam); - - [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern IntPtr CreateWindowEx(uint exStyle, string className, - string windowName, uint style, int x, int y, int width, int height, - IntPtr parent, IntPtr menu, IntPtr instance, IntPtr param); - - [DllImport("user32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool DestroyWindow(IntPtr window); - - [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern IntPtr FindWindow(string? className, string? windowName); - - [DllImport("user32.dll", SetLastError = true)] - private static extern IntPtr SendMessageTimeout(IntPtr window, uint message, - IntPtr wParam, IntPtr lParam, uint flags, uint timeout, out IntPtr result); - - [DllImport("user32.dll", SetLastError = true)] - private static extern uint GetWindowThreadProcessId(IntPtr window, out uint processId); - - [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - private static extern IntPtr GetModuleHandle(string? moduleName); -} diff --git a/apps/windows/Keepassity.Mock/TrayIcon.cs b/apps/windows/Keepassity.Mock/TrayIcon.cs deleted file mode 100644 index 61f7dfd..0000000 --- a/apps/windows/Keepassity.Mock/TrayIcon.cs +++ /dev/null @@ -1,605 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-or-later -using H.NotifyIcon; -using H.NotifyIcon.Core; -using Microsoft.UI.Windowing; -using Microsoft.UI.Xaml; -using Microsoft.UI.Xaml.Controls; -using Microsoft.UI.Xaml.Controls.Primitives; -using Microsoft.UI.Xaml.Media; -using System.Runtime.InteropServices; -using Windows.UI; -using WinRT.Interop; - -namespace Keepassity.Mock; - -/// -/// WinUI notification-area icon with a native WinUI menu surface. -/// -/// There is no first-party tray-icon API in WinUI 3; the supported approach is -/// Shell_NotifyIcon (provides the icon and the WM_CONTEXTMENU callback) plus a -/// WinUI for the menu. A flyout needs a XamlRoot, so a -/// small invisible host window is moved to the notification icon before showing -/// the menu. This is the same pattern the WinUIEx TrayIcon uses: the host is -/// positioned with Shell_NotifyIconGetRect, the flyout is shown with -/// Position=(0,0) and an ExclusionRect covering the icon, and the host takes the -/// foreground so the menu is above the taskbar and the overflow flyout. -/// -public sealed class TrayIcon : IDisposable -{ - private const int GwlExStyle = -20; - private const nint WsExTransparent = 0x00000020; - private const nint WsExToolWindow = 0x00000080; - private const nint WsExLayered = 0x00080000; - private const uint LwaAlpha = 0x00000002; - - private readonly TaskbarIcon _icon; - private readonly MenuFlyout _menu; - private readonly MenuFlyoutItem _lockItem; - private System.Drawing.Icon? _ownedIcon; - private Window? _anchorWindow; - private Border? _anchor; - private ElementTheme _theme; - private IntPtr _previousForeground; - private bool _actionInvoked; - private bool _anchorLoaded; - private bool _disposed; - - [StructLayout(LayoutKind.Sequential)] - private struct NativePoint - { - public int X; - public int Y; - } - - [StructLayout(LayoutKind.Sequential)] - private struct NativeRect - { - public int Left; - public int Top; - public int Right; - public int Bottom; - } - - [StructLayout(LayoutKind.Sequential)] - private struct NotifyIconIdentifier - { - public uint Size; - public IntPtr Window; - public uint Id; - public Guid Guid; - } - - [DllImport("user32.dll")] - private static extern bool GetCursorPos(out NativePoint point); - - [DllImport("user32.dll")] - private static extern IntPtr GetForegroundWindow(); - - [DllImport("user32.dll")] - private static extern bool SetForegroundWindow(IntPtr window); - - [DllImport("user32.dll")] - private static extern uint GetWindowThreadProcessId(IntPtr window, out uint processId); - - [DllImport("user32.dll")] - private static extern nint GetWindowLongPtr(nint window, int index); - - [DllImport("user32.dll")] - private static extern nint SetWindowLongPtr(nint window, int index, nint value); - - [DllImport("user32.dll")] - private static extern bool SetLayeredWindowAttributes(nint window, uint colorKey, - byte alpha, uint flags); - - [DllImport("shell32.dll")] - private static extern int Shell_NotifyIconGetRect(ref NotifyIconIdentifier identifier, - out NativeRect iconLocation); - - public TrayIcon(string toolTip, ElementTheme theme, string? iconPath, Action show, - Action lockAction, Action exit) - { - _theme = theme; - - var showItem = new MenuFlyoutItem - { - Text = "Show keepassity", - Icon = CreateIcon("\uE8A7"), - }; - showItem.Click += (_, _) => - { - _actionInvoked = true; - Invoke(show); - }; - - _lockItem = new MenuFlyoutItem - { - Text = "Lock", - Icon = CreateIcon("\uE72E"), - IsEnabled = false, - }; - _lockItem.Click += (_, _) => - { - _actionInvoked = true; - Invoke(lockAction); - }; - - var exitItem = new MenuFlyoutItem - { - Text = "Exit keepassity", - Icon = CreateIcon("\uE7E8"), - }; - exitItem.Click += (_, _) => - { - _actionInvoked = true; - Invoke(exit); - }; - - _menu = new MenuFlyout - { - Items = - { - showItem, - _lockItem, - new MenuFlyoutSeparator(), - exitItem, - }, - }; - _menu.Opened += OnMenuOpened; - _menu.Closed += (_, _) => OnMenuClosed(); - _menu.ShouldConstrainToRootBounds = false; - - _icon = new TaskbarIcon - { - ToolTipText = toolTip, - MenuActivation = PopupActivationMode.None, - RequestedTheme = theme, - NoLeftClickDelay = true, - LeftClickCommand = new TrayCommand(show), - DoubleClickCommand = new TrayCommand(show), - RightClickCommand = new TrayCommand(OpenMenuAtIcon), - }; - // Prefer the real application artwork. H.NotifyIcon accepts a - // System.Drawing.Icon directly for the notification-area icon; the - // framework keeps using the icon for the lifetime of the tray icon, so - // the instance is owned and disposed here. - if (!TrySetApplicationIcon(iconPath)) - { - _icon.IconSource = new GeneratedIconSource - { - Text = "K", - FontSize = 34, - FontWeight = Microsoft.UI.Text.FontWeights.Bold, - Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255)), - Background = new SolidColorBrush(Color.FromArgb(255, 0, 120, 212)), - }; - } - _icon.ForceCreate(); - } - - private bool TrySetApplicationIcon(string? iconPath) - { - if (string.IsNullOrWhiteSpace(iconPath) || !File.Exists(iconPath)) - { - AppLog.Warn("tray icon: app.ico asset is missing; using the generated fallback"); - return false; - } - try - { - _ownedIcon = new System.Drawing.Icon(iconPath); - _icon.Icon = _ownedIcon; - AppLog.Info("tray icon: loaded Assets/app.ico"); - return true; - } - catch (Exception ex) - { - AppLog.Error("tray icon: app.ico could not be loaded", ex); - return false; - } - } - - public bool Available => !_disposed && _icon.IsCreated; - - public UIElement? Element => _icon; - - public void ApplyTheme(ElementTheme theme) - { - _theme = theme; - _icon.RequestedTheme = theme; - if (_anchorWindow?.Content is FrameworkElement root) - { - root.RequestedTheme = theme; - } - } - - /// - /// Reflects the vault state in the menu and the tray tooltip. The Lock command - /// is only meaningful while a database is open. - /// - public void SetVaultState(bool unlocked, string? databaseName) - { - if (_disposed) - { - return; - } - _lockItem.IsEnabled = unlocked; - string state = unlocked ? "unlocked" : "locked"; - _icon.ToolTipText = string.IsNullOrWhiteSpace(databaseName) - ? $"keepassity - {state}" - : $"keepassity - {databaseName} ({state})"; - } - - /// - /// Test hook: opens the context menu at a physical screen position so an - /// automated capture can inspect the rendered menu without pointer input. - /// - public void ShowMenuAt(int x, int y) - { - if (_disposed) - { - return; - } - ShowMenu(x, y, 0, 0); - } - - /// - /// Test hook: opens the context menu anchored to the notification icon (the - /// same path a real right-click uses) instead of at explicit coordinates. - /// - public void ShowMenuAtIconForTest() - { - if (_disposed) - { - return; - } - OpenMenuAtIcon(); - } - - public void ShowInfo(string title, string message) - { - if (_disposed) - { - return; - } - _icon.ShowNotification(title, message); - } - - private void OpenMenuAtIcon() - { - if (_disposed) - { - return; - } - if (TryGetIconRect(out int x, out int y, out int width, out int height)) - { - ShowMenu(x, y, width, height); - return; - } - if (GetCursorPos(out NativePoint point)) - { - ShowMenu(point.X, point.Y, 0, 0); - } - } - - private bool TryGetIconRect(out int x, out int y, out int width, out int height) - { - x = y = width = height = 0; - try - { - H.NotifyIcon.Core.TrayIcon tray = _icon.TrayIcon; - if (tray is null) - { - return false; - } - NotifyIconIdentifier identifier = new() - { - Size = (uint)Marshal.SizeOf(), - Window = (IntPtr)tray.WindowHandle, - Id = 0, - Guid = tray.Id, - }; - int hresult = Shell_NotifyIconGetRect(ref identifier, out NativeRect rect); - if (hresult < 0 || rect.Right <= rect.Left || rect.Bottom <= rect.Top) - { - return false; - } - x = rect.Left; - y = rect.Top; - width = rect.Right - rect.Left; - height = rect.Bottom - rect.Top; - return true; - } - catch - { - return false; - } - } - - private void ShowMenu(int x, int y, int iconWidth, int iconHeight) - { - if (_menu.IsOpen) - { - CloseMenu(); - return; - } - EnsureAnchorWindow(); - if (_anchorWindow is null || _anchor is null) - { - return; - } - try - { - _previousForeground = GetForegroundWindow(); - _actionInvoked = false; - _iconWidth = iconWidth; - _iconHeight = iconHeight; - _anchorX = x; - _anchorY = y; - _anchorWindow.AppWindow.MoveAndResize( - new Windows.Graphics.RectInt32(x, y, 1, 1)); - if (!_anchorLoaded || _anchor.XamlRoot is null) - { - _anchor.Loaded -= OnAnchorLoaded; - _anchor.Loaded += OnAnchorLoaded; - _anchorWindow.AppWindow.Show(); - return; - } - PresentMenu(); - } - catch (Exception ex) - { - AppLog.Error("tray menu failed to open", ex); - } - } - - private int _iconWidth; - private int _iconHeight; - private int _anchorX; - private int _anchorY; - - private void OnAnchorLoaded(object sender, RoutedEventArgs e) - { - _anchor!.Loaded -= OnAnchorLoaded; - _anchorLoaded = true; - PresentMenu(); - } - - private void PresentMenu() - { - if (_disposed || _anchorWindow is null || _anchor is null || _menu.IsOpen) - { - return; - } - nint handle = WindowNative.GetWindowHandle(_anchorWindow); - double scale = _anchor.XamlRoot?.RasterizationScale ?? 1.0; - _anchorWindow.Activate(); - _anchorWindow.AppWindow.Show(); - _ = SetForegroundWindow(handle); - try - { - _menu.ShowAt(_anchor, new FlyoutShowOptions - { - Position = new Windows.Foundation.Point(0, 0), - Placement = ChoosePlacement(), - ExclusionRect = new Windows.Foundation.Rect( - 0, 0, _iconWidth / scale, _iconHeight / scale), - }); - AppLog.Info("tray menu shown"); - } - catch (Exception ex) - { - AppLog.Error("tray menu failed to open", ex); - } - } - - /// - /// Picks the side of the anchor with more room. Menus anchored near the top - /// edge (top taskbar) open down and to the right; menus near the bottom edge - /// open up. Near the right edge the menu is right-aligned to stay on screen. - /// - private FlyoutPlacementMode ChoosePlacement() - { - DisplayArea area = DisplayArea.GetFromPoint( - new Windows.Graphics.PointInt32(_anchorX, _anchorY), - DisplayAreaFallback.Nearest); - Windows.Graphics.RectInt32 work = area.WorkArea; - TrayMenuPlacement.Result placement = TrayMenuPlacement.Choose( - _anchorX, _anchorY, _iconWidth, _iconHeight, - work.Y, work.X + work.Width, work.Y + work.Height); - bool below = placement.Side == TrayMenuPlacement.VerticalSide.Below; - return below - ? (placement.RightAligned - ? FlyoutPlacementMode.BottomEdgeAlignedRight - : FlyoutPlacementMode.BottomEdgeAlignedLeft) - : (placement.RightAligned - ? FlyoutPlacementMode.TopEdgeAlignedRight - : FlyoutPlacementMode.TopEdgeAlignedLeft); - } - - private void OnMenuOpened(object? sender, object e) - { - // The flyout presenter is a separate visual root and does not inherit the - // app theme from the anchor element, so pin the theme explicitly. - if (sender is FrameworkElement presenter) - { - presenter.RequestedTheme = _theme; - } - AppLog.Info("tray menu opened"); - } - - private void CloseMenu() - { - try - { - _menu.Hide(); - } - catch (Exception ex) - { - AppLog.Error("tray menu failed to close", ex); - } - } - - private void OnMenuClosed() - { - AppLog.Info("tray menu closed"); - try - { - _anchorWindow?.AppWindow.Hide(); - } - catch - { - // Best-effort cleanup. - } - RestorePreviousForeground(); - } - - private void RestorePreviousForeground() - { - IntPtr previous = _previousForeground; - _previousForeground = IntPtr.Zero; - if (previous == IntPtr.Zero || _actionInvoked || _disposed) - { - return; - } - IntPtr foreground = GetForegroundWindow(); - _ = GetWindowThreadProcessId(foreground, out uint foregroundProcess); - if (foregroundProcess != (uint)Environment.ProcessId) - { - // The user dismissed the menu by activating another application; - // leave that application in front. - return; - } - _ = SetForegroundWindow(previous); - } - - private void EnsureAnchorWindow() - { - if (_anchorWindow is not null) - { - return; - } - - _anchor = new Border - { - Width = 1, - Height = 1, - HorizontalAlignment = HorizontalAlignment.Left, - VerticalAlignment = VerticalAlignment.Top, - Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent), - }; - var root = new Grid - { - RequestedTheme = _theme, - Background = new SolidColorBrush(Microsoft.UI.Colors.Transparent), - }; - root.Children.Add(_anchor); - - var window = new Window { Content = root }; - nint handle = WindowNative.GetWindowHandle(window); - Microsoft.UI.WindowId windowId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(handle); - AppWindow appWindow = AppWindow.GetFromWindowId(windowId); - appWindow.IsShownInSwitchers = false; - if (appWindow.Presenter is OverlappedPresenter presenter) - { - presenter.IsAlwaysOnTop = true; - presenter.IsResizable = false; - presenter.IsMaximizable = false; - presenter.IsMinimizable = false; - presenter.SetBorderAndTitleBar(false, false); - } - MakeTransparent(handle); - window.Activated += (_, args) => - { - if (args.WindowActivationState == WindowActivationState.Deactivated && _menu.IsOpen) - { - CloseMenu(); - } - }; - appWindow.Hide(); - _anchorWindow = window; - AppLog.Info("tray menu anchor window ready"); - } - - private static void MakeTransparent(nint handle) - { - nint style = GetWindowLongPtr(handle, GwlExStyle); - style |= WsExToolWindow | WsExTransparent | WsExLayered; - _ = SetWindowLongPtr(handle, GwlExStyle, style); - _ = SetLayeredWindowAttributes(handle, 0, 0, LwaAlpha); - } - - private static FontIcon CreateIcon(string glyph) => new() { Glyph = glyph, FontSize = 14 }; - - private static void Invoke(Action action) - { - try - { - action(); - } - catch - { - // A tray callback must not take down the application. - } - } - - private sealed class TrayCommand : System.Windows.Input.ICommand - { - private readonly Action _action; - - public TrayCommand(Action action) => _action = action; - - public event EventHandler? CanExecuteChanged - { - add { } - remove { } - } - - public bool CanExecute(object? parameter) => true; - - public void Execute(object? parameter) => Invoke(_action); - } - - public void Dispose() - { - if (_disposed) - { - return; - } - if (_menu.IsOpen) - { - try - { - _menu.Hide(); - } - catch - { - // Best-effort cleanup. - } - } - _disposed = true; - try - { - _anchorWindow?.Close(); - } - catch - { - // Best-effort cleanup. - } - try - { - _icon.Dispose(); - } - catch - { - // Best-effort cleanup. - } - try - { - _ownedIcon?.Dispose(); - _ownedIcon = null; - } - catch - { - // Best-effort cleanup. - } - } -} diff --git a/apps/windows/Keepassity.ViewModels/AccessibilityText.cs b/apps/windows/Keepassity.ViewModels/AccessibilityText.cs new file mode 100644 index 0000000..c4926b0 --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/AccessibilityText.cs @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +namespace Keepassity.ViewModels; + +/// +/// Pure accessibility-text decisions. The shell owns the UIA peers and the +/// live-region controls; the rules for when an announcement is worth raising +/// and how automated names are assembled live here so they stay testable +/// headless (ADR-0035). +/// +public static class AccessibilityText +{ + /// Blank or whitespace announcements would clear the live region + /// without telling the user anything, so they are skipped. + public static bool ShouldAnnounce(string? message) + { + return !string.IsNullOrWhiteSpace(message); + } + + /// Help text is only set when it says something; an empty help + /// text must not override a meaningful one. + public static bool ShouldSetHelpText(string? helpText) + { + return !string.IsNullOrWhiteSpace(helpText); + } + + /// The automation id is only set when present. + public static bool ShouldSetAutomationId(string? automationId) + { + return !string.IsNullOrWhiteSpace(automationId); + } +} diff --git a/apps/windows/Keepassity.ViewModels/DatabaseSettingsViewModel.cs b/apps/windows/Keepassity.ViewModels/DatabaseSettingsViewModel.cs new file mode 100644 index 0000000..a61b069 --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/DatabaseSettingsViewModel.cs @@ -0,0 +1,164 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Globalization; +using CommunityToolkit.Mvvm.ComponentModel; +using Keepassity.Core; + +namespace Keepassity.ViewModels; + +/// +/// State of the database settings page: the facts about the open database, the +/// switches that belong to it, and the two explicit actions' payloads. +/// +/// The WebDAV source is display-only by design: the source a database was opened +/// from is part of its identity, so changing it means opening the database from +/// the other address, not editing a field here. The page never touches the KDBX +/// file until the host saves the switches or the encryption section is confirmed. +/// +public sealed partial class DatabaseSettingsViewModel : ObservableObject +{ + private const string FormatPrefix = "KDBX "; + + private readonly VaultProfile _profile; + private readonly DatabaseSettingsDto _kdbx; + private readonly IAppText _text; + + [ObservableProperty] + private bool _syncOnSave; + + [ObservableProperty] + private double _backupRetention; + + [ObservableProperty] + private bool _recycleBinEnabled; + + [ObservableProperty] + private double _historyMaxItems; + + public DatabaseSettingsViewModel( + VaultProfile profile, + DatabaseInfoDto info, + DatabaseSettingsDto kdbx, + string databasePath, + long sizeBytes, + long? lastSyncUnix, + IAppText text) + { + _profile = profile ?? throw new ArgumentNullException(nameof(profile)); + ArgumentNullException.ThrowIfNull(info); + _kdbx = kdbx ?? throw new ArgumentNullException(nameof(kdbx)); + _text = text ?? throw new ArgumentNullException(nameof(text)); + Encryption = new EncryptionViewModel(info, text); + Name = string.IsNullOrWhiteSpace(info.Name) ? _text.T("Untitled database") : info.Name!; + DatabasePath = databasePath ?? ""; + FormatText = FormatPrefix + + (string.IsNullOrWhiteSpace(info.FormatVersion) ? "?" : info.FormatVersion) + + " · " + + (string.IsNullOrWhiteSpace(info.Cipher) ? "?" : info.Cipher); + SizeText = FormatSize(sizeBytes); + UuidText = info.VaultUuid; + LastSyncText = lastSyncUnix is null + ? _text.T("Never synced") + : _text.T("Last sync {0}", DateTimeOffset.FromUnixTimeSeconds(lastSyncUnix.Value) + .ToLocalTime().ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture)); + HasWebDav = !string.IsNullOrWhiteSpace(profile.WebDavUrl); + WebDavUrlText = HasWebDav ? profile.WebDavUrl! : _text.T("Not configured"); + WebDavUsernameText = string.IsNullOrWhiteSpace(profile.WebDavUsername) + ? _text.T("Not configured") + : profile.WebDavUsername!; + + _syncOnSave = profile.SyncOnSave; + _backupRetention = Math.Clamp(profile.BackupRetention, 1, 200); + _recycleBinEnabled = kdbx.RecycleBinEnabled; + _historyMaxItems = Math.Clamp(kdbx.HistoryMaxItems, 0, 10_000); + } + + /// Display name of the database. + public string Name { get; } + + /// File the page describes. + public string DatabasePath { get; } + + /// "KDBX 4.1 · aes256" — facts from the header. + public string FormatText { get; } + + /// Human-readable size of the file. + public string SizeText { get; } + + /// Root-group UUID (the database identity). + public string UuidText { get; } + + /// When the last successful sync happened, or "Never synced". + public string LastSyncText { get; } + + /// Whether this database has a WebDAV source at all. + public bool HasWebDav { get; } + + /// The source URL, or "Not configured" (read-only). + public string WebDavUrlText { get; } + + /// The user name, or "Not configured" (read-only). + public string WebDavUsernameText { get; } + + /// Encryption facts and the explicit change flow. + public EncryptionViewModel Encryption { get; } + + /// True when the per-database switches differ from the stored profile. + public bool ProfileChanged => + SyncOnSave != _profile.SyncOnSave || + Math.Round(BackupRetention) != Math.Clamp(_profile.BackupRetention, 1, 200); + + /// True when the KDBX built-in settings differ from the file. + public bool KdbxSettingsChanged => + RecycleBinEnabled != _kdbx.RecycleBinEnabled || + Math.Round(HistoryMaxItems) != Math.Clamp(_kdbx.HistoryMaxItems, 0, 10_000); + + /// Write the switches back to the profile object (host saves the file). + public void ApplyToProfile() + { + _profile.SyncOnSave = SyncOnSave; + _profile.BackupRetention = (int)Math.Clamp(Math.Round(BackupRetention), 1, 200); + } + + /// Copy of the effective KDBX settings for the core call. + public DatabaseSettingsDto ToKdbxSettings() => new() + { + RecycleBinEnabled = RecycleBinEnabled, + HistoryMaxItems = (long)Math.Clamp(Math.Round(HistoryMaxItems), 0, 10_000), + HistoryMaxSize = _kdbx.HistoryMaxSize, + }; + + partial void OnSyncOnSaveChanged(bool value) => + OnPropertyChanged(nameof(ProfileChanged)); + + partial void OnBackupRetentionChanged(double value) + { + BackupRetention = Math.Clamp(Math.Round(value), 1, 200); + OnPropertyChanged(nameof(ProfileChanged)); + } + + partial void OnRecycleBinEnabledChanged(bool value) => + OnPropertyChanged(nameof(KdbxSettingsChanged)); + + partial void OnHistoryMaxItemsChanged(double value) + { + HistoryMaxItems = Math.Clamp(Math.Round(value), 0, 10_000); + OnPropertyChanged(nameof(KdbxSettingsChanged)); + } + + private static string FormatSize(long bytes) + { + // Units are not translated: "MiB" is a unit, not a word, and a translation + // that equals the English source would only trip the catalog checker. + if (bytes >= 1024 * 1024) + { + return Math.Round(bytes / (1024.0 * 1024.0), 1) + .ToString("0.#", CultureInfo.InvariantCulture) + " MiB"; + } + if (bytes >= 1024) + { + return Math.Round(bytes / 1024.0, 1) + .ToString("0.#", CultureInfo.InvariantCulture) + " KiB"; + } + return bytes.ToString(CultureInfo.InvariantCulture) + " B"; + } +} diff --git a/apps/windows/Keepassity.ViewModels/DropTargetResolver.cs b/apps/windows/Keepassity.ViewModels/DropTargetResolver.cs new file mode 100644 index 0000000..d2fd5a7 --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/DropTargetResolver.cs @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +namespace Keepassity.ViewModels; + +/// +/// Pure drop-target decisions for the window and the group navigation. The +/// shell keeps the WinUI plumbing (DragEventArgs, NavigationViewItem, brushes); +/// what counts as a valid target, which file a drop selects and whether a move +/// would be a no-op all live here so they can be tested headless (ADR-0035). +/// +public static class DropTargetResolver +{ + public const string TopLevelTag = "all"; + + /// A dropped file only opens as a database when it is a .kdbx. + public static bool IsKdbxFile(string? fileName) + { + return fileName is not null && + fileName.EndsWith(".kdbx", StringComparison.OrdinalIgnoreCase); + } + + /// Picks the first dropped file that names a database; a drop that + /// carries no .kdbx file selects nothing. + public static string? FirstDatabaseFile(IEnumerable fileNames) + { + return fileNames.FirstOrDefault(IsKdbxFile); + } + + /// The synthetic "all entries" row resolves to the root group; a + /// row without a usable tag is not a drop target. + public static string? ResolveGroupUuid(string? itemTag, string? rootGroupUuid) + { + if (string.IsNullOrEmpty(itemTag)) + { + return null; + } + if (itemTag == TopLevelTag) + { + return string.IsNullOrEmpty(rootGroupUuid) ? null : rootGroupUuid; + } + return itemTag; + } + + /// The "all entries" row means the root group, i.e. the top level. + public static bool IsTopLevelTarget(string? itemTag) + { + return itemTag == TopLevelTag; + } + + /// A move onto the group the row already lives in would eject the + /// row from the list without changing anything, so the drop is refused. + public static bool IsSameGroupMove(string? sourceGroupUuid, string? targetGroupUuid) + { + return sourceGroupUuid is not null && sourceGroupUuid == targetGroupUuid; + } +} diff --git a/apps/windows/Keepassity.ViewModels/EncryptionViewModel.cs b/apps/windows/Keepassity.ViewModels/EncryptionViewModel.cs new file mode 100644 index 0000000..8bf514c --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/EncryptionViewModel.cs @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Globalization; +using Keepassity.Core; + +namespace Keepassity.ViewModels; + +/// One row of the encryption-parameter chooser. +/// Preset identifier understood by the core (keepass-classic …). +/// What the preset follows or what it is. +/// Encryption-strength label (offline cracking cost). +/// Compatibility label (how many clients open it). +public sealed record EncryptionChoice(string Id, string Title, string Strength, + string Compatibility); + +/// +/// The open database's encryption parameters as facts, plus the presets the user +/// may choose explicitly. +/// +/// The read-only part only states the values that are in the file header; it does +/// not grade them. The chooser lists the presets with two columns — encryption +/// strength and compatibility — and nothing else: no timings, no score, no +/// recommendation. Judgment about which one fits belongs to the user, which is +/// why this view model never picks a different preset on its own. +/// +public sealed class EncryptionViewModel +{ + public const string ClassicPreset = "keepass-classic"; + public const string KeepassXcPreset = "keepassxc"; + public const string DesktopPreset = "desktop"; + public const string StrongPreset = "strong"; + + private readonly IAppText _text; + private readonly string? _currentPresetId; + private string? _selectedId; + + public EncryptionViewModel(DatabaseInfoDto info, IAppText text) + { + ArgumentNullException.ThrowIfNull(info); + _text = text ?? throw new ArgumentNullException(nameof(text)); + Kdf = info.Kdf; + Summary = DescribeKdf(info.Kdf); + _currentPresetId = MatchPresetId(info.Kdf); + _selectedId = _currentPresetId; + Choices = new[] + { + new EncryptionChoice(ClassicPreset, + _text.T("Match the KeePass 2.x default"), + _text.T("Weak"), _text.T("Strong")), + new EncryptionChoice(KeepassXcPreset, + _text.T("Match the KeePassXC default"), + _text.T("Medium"), _text.T("Medium")), + new EncryptionChoice(DesktopPreset, + _text.T("Desktop only"), + _text.T("Strong"), _text.T("Weak")), + new EncryptionChoice(StrongPreset, + _text.T("Stronger"), + _text.T("Very strong"), _text.T("Weak")), + }; + } + + /// The KDF the file currently carries, when the header reported one. + public KdfInfoDto? Kdf { get; } + + /// The current parameters as one line ("Argon2id · 64 MiB · 3 iterations · 2 lanes"). + public string Summary { get; } + + /// The presets, in display order. + public IReadOnlyList Choices { get; } + + /// Preset the user selected, or null when the current values match none. + public string? SelectedId => _selectedId; + + /// + /// True when the selected preset differs from what the file already carries. + /// A custom profile that matches no preset starts out unselected, so the + /// dialog cannot "change" anything until the user picks a row. + /// + public bool CanApply => _selectedId is not null && _selectedId != _currentPresetId; + + /// Select a preset row; unknown identifiers are ignored. + public void Select(string? id) + { + if (id is null) + { + return; + } + if (Choices.Any(choice => choice.Id == id)) + { + _selectedId = id; + } + } + + /// The preset whose values exactly equal , if any. + public static string? MatchPresetId(KdfInfoDto? kdf) + { + if (kdf is null) + { + return null; + } + if (kdf.Type == "aes-kdf") + { + return kdf.Rounds == 600_000 ? ClassicPreset : null; + } + if (kdf.Type is not ("argon2id" or "argon2d")) + { + return null; + } + uint memory = kdf.MemoryMib ?? (kdf.MemoryKib ?? 0) / 1024; + return (memory, kdf.Iterations, kdf.Parallelism) switch + { + (64, 3, 2) => KeepassXcPreset, + (128, 6, 4) => DesktopPreset, + (256, 8, 4) => StrongPreset, + _ => null, + }; + } + + private string DescribeKdf(KdfInfoDto? kdf) + { + if (kdf is null || string.IsNullOrEmpty(kdf.Type)) + { + return _text.T("Not reported by the file header"); + } + if (kdf.Type == "aes-kdf") + { + return _text.T("AES-KDF · {0} rounds", + (kdf.Rounds ?? 0).ToString(CultureInfo.InvariantCulture)); + } + string name = kdf.Type == "argon2d" ? "Argon2d" : "Argon2id"; + uint memory = kdf.MemoryMib ?? (kdf.MemoryKib ?? 0) / 1024; + return _text.T("{0} · {1} MiB · {2} iterations · {3} lanes", + name, + memory.ToString(CultureInfo.InvariantCulture), + (kdf.Iterations ?? 0).ToString(CultureInfo.InvariantCulture), + (kdf.Parallelism ?? 0).ToString(CultureInfo.InvariantCulture)); + } +} diff --git a/apps/windows/Keepassity.ViewModels/EntryDetailViewModel.cs b/apps/windows/Keepassity.ViewModels/EntryDetailViewModel.cs new file mode 100644 index 0000000..00b68c1 --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/EntryDetailViewModel.cs @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using CommunityToolkit.Mvvm.ComponentModel; + +namespace Keepassity.ViewModels; + +/// +/// One entry as the detail panel needs it. Pure data; the shell maps the FFI +/// DTO to this record and the view model never sees WinUI. +/// +public readonly record struct EntryDetailInput( + string Title, + string GroupName, + string Username, + string PasswordSecret, + string Url, + string Notes, + IReadOnlyList Tags, + string? CustomFieldName, + string? CustomFieldValue, + bool HasTotp); + +/// +/// State and display strings for the detail panel. The view binds these values; +/// visibility remains a view concern (the view maps the booleans to Visibility). +/// +public sealed class EntryDetailViewModel : ObservableObject +{ + private static readonly string PasswordMask = new('\u2022', 12); + + private string _title = string.Empty; + private string _subtitle = string.Empty; + private string _username = string.Empty; + private string _passwordSecret = string.Empty; + private string _url = string.Empty; + private string _notes = string.Empty; + private string _tags = string.Empty; + private string _customFieldName = string.Empty; + private string _customFieldValue = string.Empty; + private bool _hasUsername; + private bool _hasPassword; + private bool _hasUrl; + private bool _hasTags; + private bool _hasNotes; + private bool _hasCustomField; + private bool _hasTotp; + private bool _passwordVisible; + + public string Title => _title; + public string Subtitle => _subtitle; + public string Username => _username; + public string Url => _url; + public string Notes => _notes; + public string Tags => _tags; + public string CustomFieldName => _customFieldName; + public string CustomFieldValue => _customFieldValue; + public bool HasUsername => _hasUsername; + public bool HasPassword => _hasPassword; + public bool HasUrl => _hasUrl; + public bool HasTags => _hasTags; + public bool HasNotes => _hasNotes; + public bool HasCustomField => _hasCustomField; + public bool HasTotp => _hasTotp; + + /// The password shown in the panel: mask unless revealed. + public string PasswordText => + !_hasPassword ? string.Empty : _passwordVisible ? _passwordSecret : PasswordMask; + + // Dividers sit between fields that are actually shown. + public bool ShowUsernameDivider => _hasUsername && (_hasPassword || _hasUrl || _hasTags); + public bool ShowPasswordDivider => _hasPassword && (_hasUrl || _hasTags); + public bool ShowUrlDivider => _hasUrl && _hasTags; + + public void Load(EntryDetailInput input) + { + _title = input.Title; + _subtitle = input.GroupName; + _username = input.Username; + _passwordSecret = input.PasswordSecret; + _url = input.Url; + _notes = input.Notes; + _tags = input.Tags.Count > 0 ? string.Join(" \u00b7 ", input.Tags) : string.Empty; + _customFieldName = input.CustomFieldName ?? string.Empty; + _customFieldValue = input.CustomFieldValue ?? string.Empty; + _hasUsername = !string.IsNullOrWhiteSpace(input.Username); + _hasPassword = !string.IsNullOrEmpty(input.PasswordSecret); + _hasUrl = !string.IsNullOrWhiteSpace(input.Url); + _hasTags = input.Tags.Count > 0; + _hasNotes = !string.IsNullOrWhiteSpace(input.Notes); + _hasCustomField = !string.IsNullOrEmpty(input.CustomFieldName); + _hasTotp = input.HasTotp; + _passwordVisible = false; + RaiseAll(); + } + + public void Clear(string emptyTitle) + { + _title = emptyTitle; + _subtitle = string.Empty; + _username = string.Empty; + _passwordSecret = string.Empty; + _url = string.Empty; + _notes = string.Empty; + _tags = string.Empty; + _customFieldName = string.Empty; + _customFieldValue = string.Empty; + _hasUsername = false; + _hasPassword = false; + _hasUrl = false; + _hasTags = false; + _hasNotes = false; + _hasCustomField = false; + _hasTotp = false; + _passwordVisible = false; + RaiseAll(); + } + + public void SetPasswordVisible(bool visible) + { + if (_passwordVisible == visible) + { + return; + } + _passwordVisible = visible; + OnPropertyChanged(nameof(PasswordText)); + } + + private void RaiseAll() + { + OnPropertyChanged(nameof(Title)); + OnPropertyChanged(nameof(Subtitle)); + OnPropertyChanged(nameof(Username)); + OnPropertyChanged(nameof(Url)); + OnPropertyChanged(nameof(Notes)); + OnPropertyChanged(nameof(Tags)); + OnPropertyChanged(nameof(CustomFieldName)); + OnPropertyChanged(nameof(CustomFieldValue)); + OnPropertyChanged(nameof(HasUsername)); + OnPropertyChanged(nameof(HasPassword)); + OnPropertyChanged(nameof(HasUrl)); + OnPropertyChanged(nameof(HasTags)); + OnPropertyChanged(nameof(HasNotes)); + OnPropertyChanged(nameof(HasCustomField)); + OnPropertyChanged(nameof(HasTotp)); + OnPropertyChanged(nameof(PasswordText)); + OnPropertyChanged(nameof(ShowUsernameDivider)); + OnPropertyChanged(nameof(ShowPasswordDivider)); + OnPropertyChanged(nameof(ShowUrlDivider)); + } +} diff --git a/apps/windows/Keepassity.ViewModels/EntryEditorViewModel.cs b/apps/windows/Keepassity.ViewModels/EntryEditorViewModel.cs new file mode 100644 index 0000000..2ec99e6 --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/EntryEditorViewModel.cs @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +namespace Keepassity.ViewModels; + +/// Validated TOTP value produced by the entry editor. +public readonly record struct TotpEditorValue( + string SecretBase32, + string Algorithm, + int Digits, + int Period); + +/// +/// The entry editor's data and normalization rules. The dialog controls stay in +/// the shell (they are platform objects), but the values they produce are +/// normalized and validated here so create/edit behave the same and are +/// testable without WinUI. +/// +public sealed class EntryEditorViewModel +{ + public string? Uuid { get; private init; } + public string? GroupUuid { get; private init; } + public bool IsNew => Uuid is null; + + public string Title { get; set; } = string.Empty; + public string Username { get; set; } = string.Empty; + public string Password { get; set; } = string.Empty; + public string Url { get; set; } = string.Empty; + public string TagsText { get; set; } = string.Empty; + public string Notes { get; set; } = string.Empty; + + public bool HasExistingTotp { get; private init; } + public string TotpSecret { get; set; } = string.Empty; + public string TotpAlgorithm { get; set; } = "SHA1"; + public string TotpDigits { get; set; } = "6"; + public int TotpPeriod { get; set; } = 30; + + public static EntryEditorViewModel New(string groupUuid) => new() + { + GroupUuid = groupUuid, + }; + + public static EntryEditorViewModel FromEntry( + string uuid, + string title, + string username, + string password, + string url, + IReadOnlyList tags, + string notes, + string? totpSecret, + string? totpAlgorithm, + int? totpDigits, + int? totpPeriod) => new() + { + Uuid = uuid, + Title = title, + Username = username, + Password = password, + Url = url, + TagsText = string.Join(", ", tags), + Notes = notes, + HasExistingTotp = !string.IsNullOrEmpty(totpSecret), + TotpSecret = totpSecret ?? string.Empty, + TotpAlgorithm = NormalizeAlgorithm(totpAlgorithm), + TotpDigits = NormalizeDigits(totpDigits).ToString(), + TotpPeriod = NormalizePeriod(totpPeriod), + }; + + /// + /// Title used when creating: a blank title becomes the localized placeholder + /// so an entry is never created with an empty, unclickable row. + /// + public string CreateTitle(string untitledTitle) + { + string trimmed = Title.Trim(); + return trimmed.Length > 0 ? trimmed : untitledTitle; + } + + public string UpdateTitle() => Title.Trim(); + public string NormalizedUsername() => Username.Trim(); + public string NormalizedUrl() => Url.Trim(); + + /// Comma-separated tags, trimmed, de-duplicated case-insensitively. + public List TagList() => ParseTags(TagsText); + + public static List ParseTags(string text) => text + .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + + /// True when an existing TOTP is cleared by leaving the secret empty. + public bool ShouldDeleteTotp => + HasExistingTotp && string.IsNullOrWhiteSpace(TotpSecret); + + /// Non-empty TOTP value with safe defaults, or null when none. + public TotpEditorValue? BuildTotp() + { + string secret = TotpSecret.Trim(); + if (secret.Length == 0) + { + return null; + } + return new TotpEditorValue( + secret, + NormalizeAlgorithm(TotpAlgorithm), + NormalizeDigits(int.TryParse(TotpDigits, out int digits) ? digits : null), + NormalizePeriod(TotpPeriod)); + } + + private static string NormalizeAlgorithm(string? algorithm) => algorithm switch + { + "SHA256" => "SHA256", + "SHA512" => "SHA512", + _ => "SHA1", + }; + + private static int NormalizeDigits(int? digits) => digits == 8 ? 8 : 6; + + private static int NormalizePeriod(int? period) => + Math.Clamp(period ?? 30, 1, 300); +} diff --git a/apps/windows/Keepassity.ViewModels/EntryListProjection.cs b/apps/windows/Keepassity.ViewModels/EntryListProjection.cs new file mode 100644 index 0000000..cc55eab --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/EntryListProjection.cs @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Text; + +namespace Keepassity.ViewModels; + +/// +/// The middle column's projection: filter by TOTP, order by title/modified/group, +/// and compute the cheap row identity used to avoid rebuilding the ListView when +/// the visible rows did not change. +/// +public enum EntrySort +{ + Title, + Modified, + Group, +} + +public static class EntryListProjection +{ + public static List Visible(IEnumerable rows, EntrySort sort, + bool onlyTotp) + { + IEnumerable visible = rows; + if (onlyTotp) + { + visible = visible.Where(row => row.HasTotp); + } + return sort switch + { + EntrySort.Modified => visible + .OrderByDescending(row => row.ModifiedUnix) + .ToList(), + EntrySort.Group => visible + .OrderBy(row => row.GroupName, StringComparer.CurrentCultureIgnoreCase) + .ThenBy(row => row.Title, StringComparer.CurrentCultureIgnoreCase) + .ToList(), + _ => visible + .OrderBy(row => row.Title, StringComparer.CurrentCultureIgnoreCase) + .ToList(), + }; + } + + /// + /// Cheap identity of the rendered rows. A following reload with the same + /// identity is not re-rendered, so selection and scroll survive merges and + /// moves that do not change what the user sees. + /// + public static string Fingerprint(IEnumerable rows, string title) + { + var builder = new StringBuilder(title); + foreach (EntryRowInput row in rows) + { + builder.Append('\n') + .Append(row.Uuid).Append('|') + .Append(row.GroupUuid).Append('|') + .Append(row.GroupName).Append('|') + .Append(row.Title).Append('|') + .Append(row.Username).Append('|') + .Append(row.Url).Append('|') + .Append(row.HasTotp ? '1' : '0'); + } + return builder.ToString(); + } +} diff --git a/apps/windows/Keepassity.ViewModels/EntryRowInput.cs b/apps/windows/Keepassity.ViewModels/EntryRowInput.cs new file mode 100644 index 0000000..b97528d --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/EntryRowInput.cs @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +namespace Keepassity.ViewModels; + +/// +/// One entry as the list needs it. The shell maps the FFI DTO to this record and +/// then works only through the view models, so sorting, filtering and the row's +/// display strings are testable without WinUI. +/// +public readonly record struct EntryRowInput( + string Uuid, + string GroupUuid, + string GroupName, + string Title, + string Username, + string Url, + bool HasTotp, + long ModifiedUnix); diff --git a/apps/windows/Keepassity.ViewModels/EntryRowViewModel.cs b/apps/windows/Keepassity.ViewModels/EntryRowViewModel.cs new file mode 100644 index 0000000..98ff101 --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/EntryRowViewModel.cs @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Keepassity.ViewModels; + +/// +/// Presentation state for one row in the entry list. Deliberately free of +/// WinUI types: the avatar is a hex color and the template converts it to a +/// brush, while TOTP visibility is a boolean. +/// +public class EntryRowViewModel : INotifyPropertyChanged +{ + private static readonly string[] AvatarPalette = + { + "#0078D4", + "#8764B8", + "#107C10", + "#CA5010", + "#0099BC", + "#C50F1F", + }; + + private string _groupUuid; + private string _groupName; + private string _secondary; + + public EntryRowViewModel(EntryRowInput input) + { + Uuid = input.Uuid; + _groupUuid = input.GroupUuid; + _groupName = input.GroupName; + Title = input.Title; + Username = input.Username; + Url = input.Url; + HasTotp = input.HasTotp; + _secondary = SecondaryFor(input.Username, input.Url, input.GroupName); + Initial = input.Title.Length > 0 ? input.Title[..1].ToUpperInvariant() : "?"; + int hash = 0; + foreach (char character in input.Uuid) + { + hash = unchecked((hash * 31) + character); + } + AvatarColor = AvatarPalette[(hash & int.MaxValue) % AvatarPalette.Length]; + } + + public event PropertyChangedEventHandler? PropertyChanged; + + public string Uuid { get; } + public string GroupUuid => _groupUuid; + public string GroupName => _groupName; + public string Title { get; } + public string Username { get; } + public string Url { get; } + public string Secondary => _secondary; + public bool HasTotp { get; } + public string Initial { get; } + + /// Hex color such as #0078D4; the view converts it. + public string AvatarColor { get; } + + /// + /// Updates the group shown for an entry that stays visible after a move (All + /// entries / search view). Mutating the existing item keeps the ListView's + /// selection and scroll position instead of rebuilding the middle column. + /// + public void UpdateGroup(string groupUuid, string groupName) + { + if (_groupUuid == groupUuid && _groupName == groupName) + { + return; + } + _groupUuid = groupUuid; + _groupName = groupName; + _secondary = SecondaryFor(Username, Url, groupName); + OnPropertyChanged(nameof(GroupUuid)); + OnPropertyChanged(nameof(GroupName)); + OnPropertyChanged(nameof(Secondary)); + } + + private static string SecondaryFor(string username, string url, string groupName) + => !string.IsNullOrWhiteSpace(username) + ? username + : Uri.TryCreate(url, UriKind.Absolute, out Uri? uri) && + !string.IsNullOrWhiteSpace(uri.Host) + ? uri.Host + : groupName; + + private void OnPropertyChanged([CallerMemberName] string? propertyName = null) + => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); +} diff --git a/apps/windows/Keepassity.ViewModels/GroupNavItem.cs b/apps/windows/Keepassity.ViewModels/GroupNavItem.cs new file mode 100644 index 0000000..d67fb0d --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/GroupNavItem.cs @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +namespace Keepassity.ViewModels; + +/// +/// One entry in the group navigation. Pure presentation data; the shell builds +/// the NavigationView items from these. +/// +public sealed class GroupNavItem +{ + public GroupNavItem(string? uuid, string name, int count, string glyph) + { + Uuid = uuid; + Name = name; + Count = count.ToString(); + Glyph = glyph; + } + + public string? Uuid { get; } + public string Name { get; } + public string Count { get; } + public string Glyph { get; } + public int CountValue => int.TryParse(Count, out int value) ? value : 0; +} diff --git a/apps/windows/Keepassity.ViewModels/GroupNavigationProjection.cs b/apps/windows/Keepassity.ViewModels/GroupNavigationProjection.cs new file mode 100644 index 0000000..eca8758 --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/GroupNavigationProjection.cs @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +namespace Keepassity.ViewModels; + +/// One group row as the navigation projection needs it. +public readonly record struct GroupNavigationInput(string Uuid, string Name); + +/// +/// Ordering rules for the group navigation: "All entries" first, then normal +/// groups in vault order, then the Templates group, then the Recycle Bin last. +/// Name classifiers are supplied by the view because a KeePass vault may store +/// the special groups under a localized name. +/// +public static class GroupNavigationProjection +{ + public static List Build( + IEnumerable groups, + string? rootUuid, + string allEntriesLabel, + int allEntriesCount, + Func countForGroup, + Func isRecycleBin, + Func isTemplates) + { + var items = new List(); + items.Add(new GroupNavItem(null, allEntriesLabel, allEntriesCount, "\uE8FD")); + + GroupNavItem? recycleBin = null; + GroupNavItem? templates = null; + var otherGroups = new List(); + foreach (GroupNavigationInput group in groups) + { + if (group.Uuid == rootUuid || string.IsNullOrWhiteSpace(group.Name)) + { + continue; + } + var item = new GroupNavItem(group.Uuid, group.Name, countForGroup(group.Uuid), + "\uE8B7"); + if (recycleBin is null && isRecycleBin(group.Name)) + { + recycleBin = item; + } + else if (templates is null && isTemplates(group.Name)) + { + templates = item; + } + else + { + otherGroups.Add(item); + } + } + items.AddRange(otherGroups); + if (templates is not null) + { + items.Add(templates); + } + if (recycleBin is not null) + { + items.Add(recycleBin); + } + return items; + } +} diff --git a/apps/windows/Keepassity.ViewModels/IAppText.cs b/apps/windows/Keepassity.ViewModels/IAppText.cs new file mode 100644 index 0000000..ffbf6b7 --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/IAppText.cs @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +namespace Keepassity.ViewModels; + +/// +/// Localized user-facing text for view models. The shell supplies the real +/// catalog-backed implementation; tests can supply a deterministic one, which +/// keeps view-model tests independent of the WinUI localization machinery. +/// +public interface IAppText +{ + /// Translate a plain English source string. + string T(string english); + + /// Translate a composite format string and apply the arguments. + string T(string format, params object?[] arguments); + + /// Translate a long string by symbolic key, with an English fallback. + string TLong(string key, string english); +} diff --git a/apps/windows/Keepassity.ViewModels/Keepassity.ViewModels.csproj b/apps/windows/Keepassity.ViewModels/Keepassity.ViewModels.csproj new file mode 100644 index 0000000..2ff0286 --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/Keepassity.ViewModels.csproj @@ -0,0 +1,15 @@ + + + net10.0 + enable + enable + Keepassity.ViewModels + false + + + + + + + + diff --git a/apps/windows/Keepassity.ViewModels/NetworkReplayPolicy.cs b/apps/windows/Keepassity.ViewModels/NetworkReplayPolicy.cs new file mode 100644 index 0000000..84d7848 --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/NetworkReplayPolicy.cs @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +namespace Keepassity.ViewModels; + +/// Why a network-return replay run does or does not happen. +public enum NetworkReplayDecision +{ + /// Connectivity returned and a sync is worth running now. + Replay, + /// No WebDAV target is configured, so there is nothing to replay. + NotConfigured, + /// The vault is locked; remote bytes cannot be touched without the key. + VaultLocked, + /// A save or sync is already running. + Busy, +} + +/// +/// Pure policy for replaying pending WebDAV edits when connectivity returns. +/// The shell owns the timer, the dispatcher hop and the NetworkChange +/// subscription; the decisions live here so they can be tested headless +/// (ADR-0035). +/// +public static class NetworkReplayPolicy +{ + /// Connectivity events arrive on a worker thread and in bursts while + /// a connection settles, so the shell debounces them through a timer. An + /// unavailable network or a window that is already closing must not arm it. + public static bool ShouldArmDebounce(bool networkAvailable, bool exitRequested) + { + return networkAvailable && !exitRequested; + } + + /// Decides what a fired debounce timer should do. Order matters: an + /// unconfigured sync target wins over a locked vault, and a locked vault wins + /// over a busy shell, because the cheapest correct answer wins. + public static NetworkReplayDecision Decide( + bool syncConfigured, bool coreOpen, bool hasDatabasePath, bool busy) + { + if (!syncConfigured) + { + return NetworkReplayDecision.NotConfigured; + } + if (!coreOpen || !hasDatabasePath) + { + return NetworkReplayDecision.VaultLocked; + } + if (busy) + { + return NetworkReplayDecision.Busy; + } + return NetworkReplayDecision.Replay; + } +} diff --git a/apps/windows/Keepassity.ViewModels/RecentDatabaseList.cs b/apps/windows/Keepassity.ViewModels/RecentDatabaseList.cs new file mode 100644 index 0000000..d534395 --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/RecentDatabaseList.cs @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.Core; + +namespace Keepassity.ViewModels; + +/// +/// Pure decisions for the start page's recent-database list: the secondary +/// line, the section visibility, the remember classification and the WebDAV +/// detection. The shell builds the actual controls; these rules stay testable +/// headless (ADR-0035). +/// +public static class RecentDatabaseList +{ + /// Second line under the display name: the remote URL for a + /// WebDAV database, otherwise the local path. + public static string SecondaryText(RecentDatabaseEntry entry) + { + return IsWebDavEntry(entry) + ? "WebDAV · " + entry.WebDavUrl + : entry.Path; + } + + /// The list shows only while no database is open and at least one + /// entry exists; the unlock form takes the section's place otherwise. + public static bool SectionVisible(bool noDatabaseOpen, int entryCount) + { + return noDatabaseOpen && entryCount > 0; + } + + /// How the current database is recorded: a WebDAV source without a + /// usable URL is stored as a plain local path; a local file never inherits + /// a stale WebDAV target. + public static (string Kind, string? Url, string? Username) RememberArguments( + bool webDavSource, string? sourceWebDavUrl, string? webDavUsername) + { + if (webDavSource && string.IsNullOrWhiteSpace(sourceWebDavUrl)) + { + // A local working copy without a known remote URL is just a path. + return ("local", null, null); + } + return webDavSource + ? ("webdav", sourceWebDavUrl, webDavUsername) + : ("local", null, null); + } + + /// An entry opens through WebDAV only when its kind says so and a + /// remote URL is actually present. + public static bool IsWebDavEntry(RecentDatabaseEntry entry) + { + return string.Equals(entry.Kind, "webdav", StringComparison.OrdinalIgnoreCase) && + !string.IsNullOrWhiteSpace(entry.WebDavUrl); + } +} diff --git a/apps/windows/Keepassity.ViewModels/SettingsHost.cs b/apps/windows/Keepassity.ViewModels/SettingsHost.cs new file mode 100644 index 0000000..bae7069 --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/SettingsHost.cs @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +namespace Keepassity.ViewModels; + +/// A language offered in the Settings picker. +public sealed record LanguageOption(string Setting, string DisplayName); + +/// Toast severity without depending on a UI framework. +public enum SettingsToastSeverity +{ + Informational, + Success, + Warning, + Error, +} + +/// Outcome of committing the Settings panel. +public sealed record SettingsApplyResult(bool Ok, bool SyncNow = false, string? Error = null); + +/// +/// Platform operations the Settings view model needs. The shell implements this +/// port; tests use a fake. Keeping it this narrow is what lets the settings +/// decisions be tested without WinUI, DPAPI or the file system. +/// +public interface ISettingsHost +{ + bool IsWebDavSource { get; } + + string AppVersion { get; } + + IReadOnlyList Languages { get; } + + void ApplyTheme(string theme); + + void ApplyLanguage(string setting); + + void SaveSettings(); + + bool HasStoredPassword(string url, string username); + + bool DeleteStoredPassword(string url, string username); + + void StorePassword(string url, string username, string password); + + Task ExportDiagnosticsAsync(); + + void ShowToast(string message, SettingsToastSeverity severity); +} diff --git a/apps/windows/Keepassity.ViewModels/SettingsViewModel.cs b/apps/windows/Keepassity.ViewModels/SettingsViewModel.cs new file mode 100644 index 0000000..691e1ad --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/SettingsViewModel.cs @@ -0,0 +1,315 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using CommunityToolkit.Mvvm.ComponentModel; +using Keepassity.Core; + +namespace Keepassity.ViewModels; + +/// +/// State and behaviour of the Settings panel. Appearance, language, clipboard, +/// auto-lock, backup retention and sync-on-save apply immediately; the WebDAV +/// source is committed only when the panel's Save button is used. The WebDAV +/// password is never stored on the view model: the view passes the current +/// password box text to , which sends it to the host's +/// DPAPI-backed credential store. +/// +public sealed partial class SettingsViewModel : ObservableObject +{ + private const string WebDavSourceNoteEnglish = + "This database was opened from WebDAV; the source URL is fixed for this " + + "session. To switch sources, lock and use Open from WebDAV… on the unlock " + + "page. The WebDAV password is stored with Windows DPAPI; clearing it does " + + "not touch the remote database."; + + private const string WebDavNoteEnglish = + "The URL must point to the .kdbx file. The WebDAV password is stored " + + "with Windows DPAPI, not in the plain settings file; clearing it does " + + "not touch the remote database."; + + private const string LicenseBodyEnglish = + "This program is free software: you can redistribute it and/or modify it " + + "under the terms of the GNU General Public License as published by the Free " + + "Software Foundation, either version 3 of the License, or (at your option) " + + "any later version. This program is distributed in the hope that it will be " + + "useful, but WITHOUT ANY WARRANTY; without even the implied warranty of " + + "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General " + + "Public License for more details; the full license text ships in the " + + "LICENSE file of the source repository."; + + private readonly AppSettings _settings; + private readonly ISettingsHost _host; + private readonly IAppText _text; + private readonly IReadOnlyList _languages; + + private int _themeIndex; + private string _selectedLanguage; + private bool _clearClipboardAfter30Seconds; + private bool _autoLockEnabled; + private bool _startMinimized; + private double _autoLockMinutes; + private double _backupRetention; + private bool _syncOnSave; + private string _webDavUrl; + private string _webDavUsername; + + [ObservableProperty] + private string _storedPasswordText = string.Empty; + + [ObservableProperty] + private bool _canClearStoredPassword; + + public SettingsViewModel(AppSettings settings, ISettingsHost host, IAppText text) + { + _settings = settings ?? throw new ArgumentNullException(nameof(settings)); + _host = host ?? throw new ArgumentNullException(nameof(host)); + _text = text ?? throw new ArgumentNullException(nameof(text)); + _languages = host.Languages; + _themeIndex = settings.Theme switch + { + "Light" => 1, + "Dark" => 2, + _ => 0, + }; + _selectedLanguage = settings.Language; + _clearClipboardAfter30Seconds = settings.ClearClipboardAfter30Seconds; + _autoLockEnabled = settings.AutoLockEnabled; + _startMinimized = settings.StartMinimized; + _autoLockMinutes = settings.AutoLockMinutes; + _backupRetention = settings.BackupRetention; + _syncOnSave = settings.SyncOnSave; + _webDavUrl = settings.WebDavUrl ?? string.Empty; + _webDavUsername = settings.WebDavUsername ?? string.Empty; + WebDavNote = host.IsWebDavSource + ? _text.TLong("Settings.WebDavSourceNote", WebDavSourceNoteEnglish) + : _text.TLong("Settings.WebDavNote", WebDavNoteEnglish); + AboutVersionLine = _text.T("Keepassity {0} · local-first KeePass-compatible client", + host.AppVersion); + LicenseBody = _text.TLong("About.LicenseBody", LicenseBodyEnglish); + NextcloudNote = _text.T( + "Nextcloud/ownCloud with two-factor authentication requires an app " + + "password. Server URL presets are offered when opening a database from " + + "WebDAV."); + RefreshStoredCredential(); + } + + public IReadOnlyList Languages => _languages; + + public bool IsWebDavSource => _host.IsWebDavSource; + + public string WebDavNote { get; } + + public string NextcloudNote { get; } + + public string AboutVersionLine { get; } + + public string LicenseBody { get; } + + /// 0 = system, 1 = light, 2 = dark. + public int ThemeIndex + { + get => _themeIndex; + set + { + if (!SetProperty(ref _themeIndex, value)) + { + return; + } + _settings.Theme = value switch + { + 1 => "Light", + 2 => "Dark", + _ => "System", + }; + _host.ApplyTheme(_settings.Theme); + _host.SaveSettings(); + } + } + + public string SelectedLanguage + { + get => _selectedLanguage; + set + { + if (string.IsNullOrWhiteSpace(value) || + !SetProperty(ref _selectedLanguage, value)) + { + return; + } + _settings.Language = value; + // The host persists the setting, applies the catalog and reopens + // the panel so every label is rendered in the new language. + _host.ApplyLanguage(value); + } + } + + public bool ClearClipboardAfter30Seconds + { + get => _clearClipboardAfter30Seconds; + set => SetAndSave(ref _clearClipboardAfter30Seconds, value, + () => _settings.ClearClipboardAfter30Seconds = value); + } + + public bool AutoLockEnabled + { + get => _autoLockEnabled; + set => SetAndSave(ref _autoLockEnabled, value, + () => _settings.AutoLockEnabled = value); + } + + public bool StartMinimized + { + get => _startMinimized; + set => SetAndSave(ref _startMinimized, value, + () => _settings.StartMinimized = value); + } + + public double AutoLockMinutes + { + get => _autoLockMinutes; + set + { + if (double.IsNaN(value)) + { + return; + } + double clamped = Math.Clamp(value, 1, 240); + SetAndSave(ref _autoLockMinutes, clamped, + () => _settings.AutoLockMinutes = (int)clamped); + } + } + + public double BackupRetention + { + get => _backupRetention; + set + { + if (double.IsNaN(value)) + { + return; + } + double clamped = Math.Clamp(value, 1, 200); + SetAndSave(ref _backupRetention, clamped, + () => _settings.BackupRetention = (int)clamped); + } + } + + public bool SyncOnSave + { + get => _syncOnSave; + set => SetAndSave(ref _syncOnSave, value, + () => _settings.SyncOnSave = value); + } + + public string WebDavUrl + { + get => _webDavUrl; + set + { + if (SetProperty(ref _webDavUrl, value ?? string.Empty)) + { + RefreshStoredCredential(); + } + } + } + + public string WebDavUsername + { + get => _webDavUsername; + set + { + if (SetProperty(ref _webDavUsername, value ?? string.Empty)) + { + RefreshStoredCredential(); + } + } + } + + /// Refresh the DPAPI credential summary for the current URL/user. + public void RefreshStoredCredential() + { + string url = _webDavUrl.Trim(); + string username = _webDavUsername.Trim(); + bool stored = url.Length > 0 && username.Length > 0 && + _host.HasStoredPassword(url, username); + StoredPasswordText = stored + ? _text.T("Password stored for {0} (Windows DPAPI).", username) + : _text.T("No stored password for this WebDAV target."); + CanClearStoredPassword = stored; + } + + /// Delete only the DPAPI entry, never the remote database. + public void ClearStoredPassword() + { + string url = _webDavUrl.Trim(); + string username = _webDavUsername.Trim(); + if (url.Length == 0 || username.Length == 0) + { + _host.ShowToast(_text.T("No stored password to clear."), + SettingsToastSeverity.Informational); + return; + } + bool cleared; + try + { + cleared = _host.DeleteStoredPassword(url, username); + } + catch (Exception ex) + { + _host.ShowToast(_text.T("Cannot clear stored password: {0}", ex.Message), + SettingsToastSeverity.Error); + return; + } + _host.ShowToast( + cleared + ? _text.T("Stored WebDAV password cleared") + : _text.T("No stored password to clear."), + cleared ? SettingsToastSeverity.Success : SettingsToastSeverity.Informational); + RefreshStoredCredential(); + } + + /// + /// Commit the application-level settings. The WebDAV source and the + /// per-database switches live on the database settings page now, so this + /// only flushes what this page owns (theme, language, clipboard, auto-lock, + /// start-minimized). It must never touch the vault's source fields: clearing + /// them here would drop a legacy source before its one-time migration. + /// + public Task ApplyAsync() + { + try + { + _host.SaveSettings(); + } + catch (Exception ex) + { + return Task.FromResult(new SettingsApplyResult(false, + Error: _text.T("Cannot save settings: {0}", ex.Message))); + } + return Task.FromResult(new SettingsApplyResult(true, false)); + } + + /// Export diagnostics through the host and report the outcome as a toast. + public async Task ExportDiagnosticsAsync() + { + try + { + string path = await _host.ExportDiagnosticsAsync().ConfigureAwait(true); + _host.ShowToast(_text.T("Diagnostics exported: {0}", path), + SettingsToastSeverity.Success); + } + catch (Exception ex) + { + _host.ShowToast(_text.T("Diagnostics export failed: {0}", ex.Message), + SettingsToastSeverity.Error); + } + } + + private void SetAndSave(ref T field, T value, Action apply) + { + if (!SetProperty(ref field, value)) + { + return; + } + apply(); + _host.SaveSettings(); + } +} diff --git a/apps/windows/Keepassity.ViewModels/SyncStatusViewModel.cs b/apps/windows/Keepassity.ViewModels/SyncStatusViewModel.cs new file mode 100644 index 0000000..325a88a --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/SyncStatusViewModel.cs @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using CommunityToolkit.Mvvm.ComponentModel; + +namespace Keepassity.ViewModels; + +/// +/// Localized sync status shown in the navigation pane. The shell stores the +/// source string and arguments (some are numeric), and the view model renders +/// them through so a language change can refresh the text +/// without rebuilding the navigation item. +/// +public sealed partial class SyncStatusViewModel : ObservableObject +{ + private readonly IAppText _appText; + private string _source = "Local only"; + private object?[] _arguments = Array.Empty(); + + [ObservableProperty] + private string _text = string.Empty; + + public SyncStatusViewModel(IAppText appText) + { + _appText = appText ?? throw new ArgumentNullException(nameof(appText)); + Refresh(); + } + + /// The untranslated source string (diagnostics and tests). + public string Source => _source; + + /// Set the status source and its format arguments. + public void Set(string source, params object?[] arguments) + { + _source = source; + _arguments = arguments; + Refresh(); + } + + /// Re-render the current status, for example after a language change. + public void Refresh() + { + Text = _arguments.Length == 0 + ? _appText.T(_source) + : _appText.T(_source, _arguments); + } +} diff --git a/apps/windows/Keepassity.ViewModels/TotpDisplayViewModel.cs b/apps/windows/Keepassity.ViewModels/TotpDisplayViewModel.cs new file mode 100644 index 0000000..5269a87 --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/TotpDisplayViewModel.cs @@ -0,0 +1,281 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using CommunityToolkit.Mvvm.ComponentModel; + +namespace Keepassity.ViewModels; + +/// A TOTP code plus the window information the display needs. +public readonly record struct TotpCodeSnapshot(string Code, int Remaining, int Period, int Digits); + +/// The core call the TOTP display needs, injectable for tests. +public interface ITotpCodeSource +{ + Task GetAsync(string uuid, long? atUnix); +} + +/// +/// The TOTP display state machine: which code is shown, the window countdown, +/// the near-boundary pre-fetch and the generation guard for entry switches. The +/// shell owns the timer and passes the current time; no WinUI type appears here. +/// +public sealed class TotpDisplayViewModel : ObservableObject +{ + private readonly ITotpCodeSource _source; + private readonly Func _nowUnix; + private readonly SemaphoreSlim _gate = new(1, 1); + + private string? _entryUuid; + private int _generation; + private TotpCodeSnapshot? _displayed; + private string? _displayedUuid; + private long _windowEndUnix = long.MaxValue; + private TotpCodeSnapshot? _prefetched; + private string? _prefetchedUuid; + private long _prefetchTargetUnix = long.MinValue; + private bool _prefetchInFlight; + private bool _hasCode; + private bool _sourceFailed; + private string _codeText = string.Empty; + private int _remainingSeconds; + private int _period; + private int _progressValue; + + public TotpDisplayViewModel(ITotpCodeSource source, Func nowUnix) + { + _source = source; + _nowUnix = nowUnix; + } + + public bool HasCode => _hasCode; + + /// + /// True when the last code request failed (the core was locked, the entry + /// vanished, the secret was rejected). The shell shows "unavailable" instead + /// of claiming that no TOTP is configured. + /// + public bool SourceFailed => _sourceFailed; + + public string CodeText => _codeText; + public int RemainingSeconds => _remainingSeconds; + public int Period => _period; + public int ProgressValue => _progressValue; + + /// The code currently displayed, for the copy command. + public string? CurrentCode => _displayed?.Code; + + /// End of the current TOTP window, used to schedule the next tick. + public long WindowEndUnix => _windowEndUnix; + + /// Switch entries; an in-flight request for the old entry is ignored. + public void SelectEntry(string? uuid) + { + if (string.Equals(_entryUuid, uuid, StringComparison.Ordinal)) + { + return; + } + _entryUuid = uuid; + _generation++; + ResetState(); + } + + public void Reset() + { + _entryUuid = null; + _generation++; + ResetState(); + } + + /// + /// Advance the display. The shell calls this once per timer tick and once + /// after selecting an entry; overlapping calls are serialized. + /// + public async Task TickAsync() + { + await _gate.WaitAsync().ConfigureAwait(false); + try + { + string? uuid = _entryUuid; + if (uuid is null) + { + ResetState(); + return; + } + long now = _nowUnix(); + if (TotpTiming.ShouldRequestCode(now, _displayed is not null, _displayedUuid, + uuid, _windowEndUnix)) + { + TotpCodeSnapshot? prefetched = _prefetched; + if (prefetched is { } candidate && _prefetchedUuid == uuid && + TotpTiming.IsPrefetchUsable(_prefetchTargetUnix, candidate.Period, now)) + { + Activate(candidate, + _prefetchTargetUnix + Math.Max(1, candidate.Period), uuid); + ClearPrefetch(); + } + else + { + ClearPrefetch(); + int generation = _generation; + TotpCodeSnapshot? code; + try + { + code = await _source.GetAsync(uuid, null).ConfigureAwait(false); + } + catch + { + // A core failure must not escape the timer callback and + // take the application down; hide the code and let the + // next tick retry. + if (generation == _generation && _entryUuid == uuid) + { + SetUnavailable(sourceFailed: true); + } + return; + } + if (generation != _generation || _entryUuid != uuid) + { + return; + } + if (code is null) + { + SetUnavailable(); + return; + } + Activate(code.Value, now + Math.Max(1, code.Value.Remaining), uuid); + } + } + + now = _nowUnix(); + int period = Math.Max(1, _displayed?.Period ?? 30); + int remaining = TotpTiming.Remaining(_windowEndUnix, now, period); + SetCountdown(period, remaining); + if (TotpTiming.ShouldPrefetch(remaining, _windowEndUnix, _prefetched is not null, + _prefetchInFlight)) + { + _prefetchInFlight = true; + _ = PrefetchAsync(uuid, _windowEndUnix, period, _generation); + } + } + finally + { + _gate.Release(); + } + } + + private async Task PrefetchAsync(string uuid, long targetUnix, int period, int generation) + { + try + { + TotpCodeSnapshot? next = await _source.GetAsync(uuid, targetUnix) + .ConfigureAwait(false); + await _gate.WaitAsync().ConfigureAwait(false); + try + { + if (next is null || generation != _generation || _entryUuid != uuid) + { + return; + } + long now = _nowUnix(); + if (now < targetUnix) + { + _prefetched = next; + _prefetchedUuid = uuid; + _prefetchTargetUnix = targetUnix; + } + else if (TotpTiming.IsPrefetchUsable(targetUnix, period, now) && + _windowEndUnix <= now) + { + Activate(next.Value, targetUnix + Math.Max(1, period), uuid); + } + } + finally + { + _gate.Release(); + } + } + catch + { + // A prefetch failure is not user-visible; the next tick requests the + // code normally. + } + finally + { + await _gate.WaitAsync().ConfigureAwait(false); + try + { + if (generation == _generation) + { + _prefetchInFlight = false; + } + } + finally + { + _gate.Release(); + } + } + } + + private void Activate(TotpCodeSnapshot code, long windowEndUnix, string uuid) + { + _displayed = code; + _displayedUuid = uuid; + _windowEndUnix = windowEndUnix; + _sourceFailed = false; + SetCode(code.Code, code.Digits); + OnPropertyChanged(nameof(SourceFailed)); + } + + private void SetCode(string code, int digits) + { + _hasCode = true; + _codeText = TotpTiming.FormatCode(code, digits); + OnPropertyChanged(nameof(HasCode)); + OnPropertyChanged(nameof(CodeText)); + OnPropertyChanged(nameof(CurrentCode)); + } + + private void SetCountdown(int period, int remaining) + { + _period = period; + _remainingSeconds = remaining; + _progressValue = period - remaining; + OnPropertyChanged(nameof(Period)); + OnPropertyChanged(nameof(RemainingSeconds)); + OnPropertyChanged(nameof(ProgressValue)); + } + + private void SetUnavailable(bool sourceFailed = false) + { + _windowEndUnix = long.MaxValue; + _hasCode = false; + _sourceFailed = sourceFailed; + _codeText = string.Empty; + _remainingSeconds = 0; + _period = 0; + _progressValue = 0; + OnPropertyChanged(nameof(HasCode)); + OnPropertyChanged(nameof(SourceFailed)); + OnPropertyChanged(nameof(CodeText)); + OnPropertyChanged(nameof(CurrentCode)); + OnPropertyChanged(nameof(Period)); + OnPropertyChanged(nameof(RemainingSeconds)); + OnPropertyChanged(nameof(ProgressValue)); + } + + private void ResetState() + { + _displayed = null; + _displayedUuid = null; + _windowEndUnix = long.MaxValue; + ClearPrefetch(); + SetUnavailable(); + OnPropertyChanged(nameof(WindowEndUnix)); + } + + private void ClearPrefetch() + { + _prefetched = null; + _prefetchedUuid = null; + _prefetchTargetUnix = long.MinValue; + _prefetchInFlight = false; + } +} diff --git a/apps/windows/Keepassity.ViewModels/TotpTiming.cs b/apps/windows/Keepassity.ViewModels/TotpTiming.cs new file mode 100644 index 0000000..31facca --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/TotpTiming.cs @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +namespace Keepassity.ViewModels; + +/// +/// Pure TOTP display timing: countdown, code formatting, the next timer tick +/// and the window-boundary decisions. Keeping this out of the shell makes the +/// off-by-one boundary behavior testable. +/// +public static class TotpTiming +{ + /// Seconds left in the current window, clamped to [0, period]. + public static int Remaining(long windowEndUnix, long nowUnix, int period) + { + int safePeriod = Math.Max(1, period); + long remaining = windowEndUnix - nowUnix; + return (int)Math.Clamp(remaining, 0, safePeriod); + } + + /// Group digits for readability: 123 456 or 1234 5678. + public static string FormatCode(string code, int digits) + { + if (digits == 8 && code.Length == 8) + { + return $"{code[..4]} {code[4..]}"; + } + if (code.Length == 6) + { + return $"{code[..3]} {code[3..]}"; + } + return code; + } + + /// + /// True when the displayed code is missing, belongs to another entry, or its + /// window has ended and a fresh code must be requested. + /// + public static bool ShouldRequestCode(long nowUnix, bool hasDisplayedCode, + string? displayedUuid, string currentUuid, long windowEndUnix) => + !hasDisplayedCode || displayedUuid != currentUuid || nowUnix >= windowEndUnix; + + /// + /// Pre-fetch the next window when fewer than three seconds remain and no + /// prefetch is already available or in flight. + /// + public static bool ShouldPrefetch(int remaining, long windowEndUnix, + bool hasPrefetched, bool prefetchInFlight) => + remaining < 3 && windowEndUnix != long.MaxValue && !hasPrefetched && + !prefetchInFlight; + + /// + /// Delay until the next timer tick. Near a window boundary the tick lands + /// just after it (15 ms) so the code never displays one tick too long. + /// + public static TimeSpan NextTick(TimeSpan untilBoundary) + { + return untilBoundary > TimeSpan.Zero && untilBoundary < TimeSpan.FromSeconds(1) + ? untilBoundary + TimeSpan.FromMilliseconds(15) + : TimeSpan.FromSeconds(1); + } + + /// + /// A prefetched code for is usable once the + /// clock reaches its window and before that window ends. + /// + public static bool IsPrefetchUsable(long targetUnix, int period, long nowUnix) => + nowUnix >= targetUnix && nowUnix < targetUnix + Math.Max(1, period); +} diff --git a/apps/windows/Keepassity.ViewModels/UnlockViewModel.cs b/apps/windows/Keepassity.ViewModels/UnlockViewModel.cs new file mode 100644 index 0000000..13adc47 --- /dev/null +++ b/apps/windows/Keepassity.ViewModels/UnlockViewModel.cs @@ -0,0 +1,245 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using CommunityToolkit.Mvvm.ComponentModel; +using Keepassity.Core; + +namespace Keepassity.ViewModels; + +/// Visual severity of the unlock status banner. +public enum UnlockStatusSeverity +{ + Informational, + Success, + Warning, + Error, +} + +/// +/// State and behaviour of the unlock surface. The view owns the password box and +/// passes its current text to ; the view model owns +/// validation, busy state, the status banner and the error classification, so +/// the whole unlock decision path is testable without WinUI. +/// +public sealed partial class UnlockViewModel : ObservableObject +{ + private readonly ICoreClient _core; + private readonly IAppText _text; + private readonly RemoteVaultOpener? _remoteOpener; + private string? _databasePath; + private PendingRemoteDatabase? _pendingRemote; + + [ObservableProperty] + private bool _isBusy; + + [ObservableProperty] + private bool _isStatusOpen; + + [ObservableProperty] + private string _statusTitle = string.Empty; + + [ObservableProperty] + private string _statusMessage = string.Empty; + + [ObservableProperty] + private UnlockStatusSeverity _statusSeverity; + + /// Whether the recovery actions (diagnostics / backups) should show. + [ObservableProperty] + private bool _recoveryVisible; + + /// + /// Core error code of the last failed attempt (CorruptDatabase, + /// BadPassword, ...). The shell uses it to offer a backup recovery for + /// a damaged database without re-parsing a status message. + /// + public string? LastErrorCode { get; private set; } + + /// + /// When the selected database was downloaded from WebDAV, the unlock opens + /// the downloaded bytes first and only then promotes them to the working + /// copy (see ). Local databases unlock as before. + /// + public UnlockViewModel(ICoreClient core, IAppText text, RemoteVaultOpener? remoteOpener = null) + { + _core = core ?? throw new ArgumentNullException(nameof(core)); + _text = text ?? throw new ArgumentNullException(nameof(text)); + _remoteOpener = remoteOpener; + } + + /// Absolute path of the database selected on the unlock surface. + public string? DatabasePath + { + get => _databasePath; + private set + { + if (SetProperty(ref _databasePath, value)) + { + OnPropertyChanged(nameof(HasDatabase)); + OnPropertyChanged(nameof(CanUnlock)); + } + } + } + + public bool HasDatabase => !string.IsNullOrWhiteSpace(_databasePath); + + /// Whether the unlock action may run right now. + public bool CanUnlock => HasDatabase && !IsBusy; + + /// Whether the password box and source buttons accept input. + public bool IsInputEnabled => !IsBusy; + + partial void OnIsBusyChanged(bool value) + { + OnPropertyChanged(nameof(CanUnlock)); + OnPropertyChanged(nameof(IsInputEnabled)); + } + + /// + /// Select a database path without unlocking. A different path clears any + /// status left over from the previous attempt, so a stale error can never be + /// mistaken for the new selection. A pending WebDAV download belongs to one + /// working copy only, so switching to another database drops it. + /// + public void SetDatabasePath(string? path) + { + string? normalized = string.IsNullOrWhiteSpace(path) ? null : path; + if (string.Equals(_databasePath, normalized, StringComparison.Ordinal)) + { + return; + } + if (_pendingRemote is not null && !string.Equals( + _pendingRemote.WorkingCopyPath, normalized, + StringComparison.OrdinalIgnoreCase)) + { + _pendingRemote = null; + } + DatabasePath = normalized; + ClearStatus(); + } + + /// + /// The downloaded WebDAV database waiting to be unlocked, or null. Its bytes + /// are opened directly so the working copy is only replaced after the master + /// password proved they decrypt. + /// + public PendingRemoteDatabase? PendingRemote => _pendingRemote; + + /// + /// Hand the downloaded remote database to the next unlock. Passing null + /// forgets it; a new download replaces the previous one. + /// + public void SetPendingRemote(PendingRemoteDatabase? pending) => _pendingRemote = pending; + + /// Whether a database-open operation (not necessarily an unlock) is running. + public void SetBusy(bool busy) => IsBusy = busy; + + /// Show the recovery actions below the status banner. + public void ShowRecovery() => RecoveryVisible = true; + + /// Hide the recovery actions. + public void HideRecovery() => RecoveryVisible = false; + + /// + /// Publish a status banner. The unlock surface is also used by the local-file, + /// WebDAV and new-database flows, so they all route their status through this + /// single state instead of writing the InfoBar directly. + /// + public void ShowStatus(string title, string message, + UnlockStatusSeverity severity, bool recovery = false) + { + StatusSeverity = severity; + StatusTitle = title; + StatusMessage = message; + RecoveryVisible = recovery; + IsStatusOpen = true; + } + + /// + /// Validate the input and open the selected database. Returns true only when + /// the native handle is successfully unlocked; failures leave a localized + /// status banner and never throw (except caller cancellation). + /// + public async Task UnlockAsync(string password, CancellationToken cancellationToken = default) + { + if (IsBusy) + { + return false; + } + if (!HasDatabase) + { + ShowError(_text.T("Cannot open database"), + _text.T("Choose a .kdbx database first."), recovery: false); + return false; + } + if (string.IsNullOrEmpty(password)) + { + ShowError(_text.T("Cannot open database"), + _text.T("Enter the master password."), recovery: false); + return false; + } + + IsBusy = true; + ClearStatus(); + LastErrorCode = null; + PendingRemoteDatabase? pending = _pendingRemote; + bool usePendingRemote = pending is not null && _remoteOpener is not null && + string.Equals(pending.WorkingCopyPath, _databasePath, + StringComparison.OrdinalIgnoreCase); + try + { + if (usePendingRemote) + { + // Open the downloaded bytes and promote them to the working copy + // only after they decrypted; a wrong password or a damaged + // download leaves the previous working copy alone. + await _remoteOpener!.OpenAsync(pending!, _core, password).ConfigureAwait(true); + _pendingRemote = null; + } + else + { + await _core.OpenAsync(_databasePath!, password).ConfigureAwait(true); + } + return true; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (CoreException ex) + { + LastErrorCode = ex.Code; + ShowError(TitleFor(ex.Code), ex.Message, recovery: true); + return false; + } + catch (Exception ex) + { + ShowError(_text.T("Cannot open database"), ex.Message, recovery: true); + return false; + } + finally + { + IsBusy = false; + } + } + + private string TitleFor(string code) => code switch + { + "BadPassword" => _text.T("Wrong master password"), + "CorruptDatabase" => _text.T("Database is damaged"), + "UnsupportedFormat" => _text.T("Unsupported database"), + _ => _text.T("Cannot open database"), + }; + + private void ShowError(string title, string message, bool recovery) + { + ShowStatus(title, message, UnlockStatusSeverity.Error, recovery); + } + + /// Dismiss the status banner and its recovery actions. + public void ClearStatus() + { + IsStatusOpen = false; + StatusTitle = string.Empty; + StatusMessage = string.Empty; + RecoveryVisible = false; + } +} diff --git a/apps/windows/Keepassity.sln b/apps/windows/Keepassity.sln index 21e7ba5..ecb2b6f 100644 --- a/apps/windows/Keepassity.sln +++ b/apps/windows/Keepassity.sln @@ -3,10 +3,12 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 18 VisualStudioVersion = 18.0.0.0 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Keepassity.Mock", "Keepassity.Mock\Keepassity.Mock.csproj", "{7D4B2A1C-5E3F-4A8B-9C6D-1F2E3A4B5C6D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Keepassity.App", "Keepassity.App\Keepassity.App.csproj", "{7D4B2A1C-5E3F-4A8B-9C6D-1F2E3A4B5C6D}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Keepassity.Core", "Keepassity.Core\Keepassity.Core.csproj", "{2ACD2930-1AFA-489D-8083-72958A12A2E1}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Keepassity.ViewModels", "Keepassity.ViewModels\Keepassity.ViewModels.csproj", "{77A5546C-7F14-4314-874B-2B1519AA87AE}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 @@ -41,6 +43,18 @@ Global {2ACD2930-1AFA-489D-8083-72958A12A2E1}.Release|Any CPU.Build.0 = Release|Any CPU {2ACD2930-1AFA-489D-8083-72958A12A2E1}.Release|x86.ActiveCfg = Release|Any CPU {2ACD2930-1AFA-489D-8083-72958A12A2E1}.Release|x86.Build.0 = Release|Any CPU + {77A5546C-7F14-4314-874B-2B1519AA87AE}.Debug|x64.ActiveCfg = Debug|Any CPU + {77A5546C-7F14-4314-874B-2B1519AA87AE}.Debug|x64.Build.0 = Debug|Any CPU + {77A5546C-7F14-4314-874B-2B1519AA87AE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {77A5546C-7F14-4314-874B-2B1519AA87AE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {77A5546C-7F14-4314-874B-2B1519AA87AE}.Debug|x86.ActiveCfg = Debug|Any CPU + {77A5546C-7F14-4314-874B-2B1519AA87AE}.Debug|x86.Build.0 = Debug|Any CPU + {77A5546C-7F14-4314-874B-2B1519AA87AE}.Release|x64.ActiveCfg = Release|Any CPU + {77A5546C-7F14-4314-874B-2B1519AA87AE}.Release|x64.Build.0 = Release|Any CPU + {77A5546C-7F14-4314-874B-2B1519AA87AE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {77A5546C-7F14-4314-874B-2B1519AA87AE}.Release|Any CPU.Build.0 = Release|Any CPU + {77A5546C-7F14-4314-874B-2B1519AA87AE}.Release|x86.ActiveCfg = Release|Any CPU + {77A5546C-7F14-4314-874B-2B1519AA87AE}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/crates/cli/src/kdf.rs b/crates/cli/src/kdf.rs new file mode 100644 index 0000000..8a0b02f --- /dev/null +++ b/crates/cli/src/kdf.rs @@ -0,0 +1,233 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! `kdf`: inspect and explicitly change the encryption parameters a file carries. +//! +//! Two modes, both IO-only on top of the core (the core stays IO-free): +//! +//! * `kdf ` prints what the header says, so a user can check a file a +//! phone refused to open. +//! * `kdf --out [--set | --from-backup ]` re-encrypts +//! with new parameters. Nothing is written until the output has been read +//! back and its header matches the request. +//! +//! Saving never changes a database's KDF on its own; this command is the +//! explicit path, and `--from-backup` restores the parameters recorded in an +//! earlier copy (for example the app's pre-save backup). + +use keepassity_core::kdbx::{reader, writer}; +use keepassity_core::model::{Argon2Kind, Database, KdfPreset, KdfSettings}; +use serde_json::{json, Value}; +use std::path::Path; + +/// Run `kdf` with the arguments after the command name. +pub fn run(args: &[String], password: &str) -> Result { + let input = args + .get(2) + .ok_or_else(|| "missing ".to_string())? + .clone(); + let set = crate::arg_value(args, "--set"); + let from_backup = crate::arg_value(args, "--from-backup"); + let output = crate::arg_value(args, "--out"); + + let bytes = std::fs::read(&input).map_err(|error| format!("cannot open {input}: {error}"))?; + let database = + reader::parse(&bytes, password).map_err(|error| format!("cannot open KDBX: {error}"))?; + + let Some(output) = output else { + if set.is_some() || from_backup.is_some() { + return Err("--set/--from-backup need --out ".to_string()); + } + println!( + "{}", + serde_json::to_string_pretty(&report(&input, &database)) + .map_err(|error| error.to_string())? + ); + return Ok(0); + }; + + if Path::new(&output) == Path::new(&input) { + return Err("refusing to write: input and output are the same path".to_string()); + } + if Path::new(&output).exists() && !args.iter().any(|arg| arg == "--overwrite") { + return Err(format!( + "refusing to overwrite existing output {output} (pass --overwrite)" + )); + } + if let Some(parent) = Path::new(&output).parent() { + if !parent.as_os_str().is_empty() && !parent.exists() { + return Err(format!( + "output directory does not exist: {}", + parent.display() + )); + } + } + + let wanted = match (set, from_backup) { + (Some(_), Some(_)) => { + return Err("use either --set or --from-backup, not both".to_string()); + } + (Some(spec), None) => parse_spec(&spec)?, + (None, Some(backup)) => { + let backup_bytes = + std::fs::read(&backup).map_err(|error| format!("cannot open {backup}: {error}"))?; + let backup_database = reader::parse(&backup_bytes, password) + .map_err(|error| format!("cannot open KDBX {backup}: {error}"))?; + current_kdf(&backup_database) + .ok_or_else(|| format!("{backup} carries no KDF settings in its outer header"))? + } + (None, None) => { + return Err("nothing to change: pass --set or --from-backup ".to_string()); + } + }; + + let before = current_kdf(&database); + let mut database = database; + database + .set_kdf(wanted.clone()) + .map_err(|error| format!("cannot apply KDF: {error}"))?; + let written = writer::write_model(&database, password) + .map_err(|error| format!("cannot write KDBX: {error}"))?; + + // Read the result back before it touches the disk: the header is what other + // clients read, so a mismatch here means the file is not what was asked for. + let verified = reader::parse(&written, password) + .map_err(|error| format!("the rewritten database is unreadable: {error}"))?; + let after = current_kdf(&verified) + .ok_or_else(|| "the rewritten database lost its KDF header".to_string())?; + if after != wanted { + return Err("the rewritten header does not match the requested KDF".to_string()); + } + + std::fs::write(&output, &written).map_err(|error| format!("cannot write {output}: {error}"))?; + + println!( + "{}", + serde_json::to_string_pretty(&json!({ + "status": "ok", + "input": input, + "output": output, + "bytes": written.len(), + "kdf_before": kdf_value(before.as_ref()), + "kdf_after": kdf_value(Some(&after)), + "verified": true, + })) + .map_err(|error| error.to_string())? + ); + Ok(0) +} + +fn report(path: &str, database: &Database) -> Value { + json!({ + "status": "ok", + "file": path, + "format_version": database.format_version, + "cipher": database.outer.as_ref().map(|header| cipher_name(header)), + "compression": database.outer.as_ref().map(|header| compression_name(header)), + "kdf": kdf_value(current_kdf(database).as_ref()), + }) +} + +fn current_kdf(database: &Database) -> Option { + database + .outer + .as_ref() + .and_then(|header| header.kdf.clone()) +} + +fn kdf_value(kdf: Option<&KdfSettings>) -> Value { + let Some(kdf) = kdf else { + return Value::Null; + }; + match kdf { + KdfSettings::Aes { rounds } => json!({ + "type": "aes-kdf", + "rounds": rounds, + "mobile_safe": kdf.is_mobile_safe(), + }), + KdfSettings::Argon2 { + kind, + iterations, + memory_kib, + parallelism, + version, + } => json!({ + "type": match kind { + Argon2Kind::D => "argon2d", + Argon2Kind::Id => "argon2id", + }, + "memory_mib": memory_kib / 1024, + "iterations": iterations, + "parallelism": parallelism, + "version": version, + "mobile_safe": kdf.is_mobile_safe(), + }), + } +} + +fn cipher_name(header: &keepassity_core::model::OuterHeader) -> &'static str { + use keepassity_core::model::OuterCipher; + match header.cipher { + OuterCipher::Aes128 => "aes128", + OuterCipher::Aes256 => "aes256", + OuterCipher::Twofish => "twofish", + OuterCipher::ChaCha20 => "chacha20", + } +} + +fn compression_name(header: &keepassity_core::model::OuterHeader) -> &'static str { + use keepassity_core::model::OuterCompression; + match header.compression { + OuterCompression::None => "none", + OuterCompression::Gzip => "gzip", + } +} + +/// Parse `keepass-classic`, `keepassxc`, `desktop`, `strong`, `aes:` or +/// `argon2id:::`. +fn parse_spec(spec: &str) -> Result { + let kdf = match spec { + "keepass-classic" | "aes" | "aes-600k" | "legacy" => KdfPreset::KeepassClassic.settings(), + "keepassxc" | "mobile" => KdfPreset::KeepassXc.settings(), + "desktop" => KdfPreset::Desktop.settings(), + "strong" => KdfPreset::Strong.settings(), + other => { + let parts: Vec<&str> = other.split(':').collect(); + match parts.as_slice() { + ["aes", rounds] => KdfSettings::Aes { + rounds: rounds + .parse() + .map_err(|_| format!("{other}: rounds must be a number"))?, + }, + [kind @ ("argon2id" | "argon2d"), memory, iterations, parallelism] => { + let memory_mib: u64 = memory + .parse() + .map_err(|_| format!("{other}: memory must be MiB as a number"))?; + KdfSettings::Argon2 { + kind: if *kind == "argon2d" { + Argon2Kind::D + } else { + Argon2Kind::Id + }, + memory_kib: u32::try_from(memory_mib.saturating_mul(1024)) + .map_err(|_| format!("{other}: memory is too large"))?, + iterations: iterations + .parse() + .map_err(|_| format!("{other}: iterations must be a number"))?, + parallelism: parallelism + .parse() + .map_err(|_| format!("{other}: parallelism must be a number"))?, + version: 0x13, + } + } + _ => { + return Err(format!( + "unknown KDF spec {other}: use keepass-classic, keepassxc, desktop, \ + strong, aes: or argon2id:::" + )); + } + } + } + }; + kdf.validate() + .map_err(|error| format!("{spec} is not a usable KDF: {error}"))?; + Ok(kdf) +} diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 3235dc7..ad4ad23 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -5,6 +5,7 @@ //! `--password-env`, or `KEEPASSITY_PASSWORD`) and print JSON unless stated. //! Exit codes: 0 ok, 2 usage, 3 authentication/key, 4 file IO, 5 KDBX format. +mod kdf; mod rewrite; mod verify; @@ -38,6 +39,7 @@ fn main() { "list" => finish(run_list(&args)), "totp" => finish(run_totp(&args)), "rewrite" => finish(read_password(&args).and_then(|pw| rewrite::run(&args, &pw))), + "kdf" => finish(read_password(&args).and_then(|pw| kdf::run(&args, &pw))), "verify" => finish(read_password(&args).and_then(|pw| verify::run(&args, &pw))), "export-model" => finish(run_export_model(&args)), "sync" => finish(run_sync(&args)), @@ -56,6 +58,8 @@ fn usage() -> &'static str { totp --entry TITLE|UUID [--at UNIX]\n\ export-model [--sha256]\n\ write: rewrite [--change-title] [--title-suffix S] [--overwrite] [--emit-title-change]\n\ + kdf (inspect the encryption parameters)\n\ + kdf --out [--set SPEC | --from-backup FILE] [--overwrite]\n\ verify [--expect-title-old OLD --expect-title-new NEW]\n\ sync: sync (local compare; network sync arrives in M4)\n\ global: --json-errors\n\ diff --git a/crates/cli/src/verify.rs b/crates/cli/src/verify.rs deleted file mode 100644 index 1f73de1..0000000 --- a/crates/cli/src/verify.rs +++ /dev/null @@ -1,546 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-or-later -//! `verify`: independent structural comparison of two KDBX files. -//! -//! Reading uses the project's established read path (`keepass 0.17`). Nothing -//! is written; failure messages contain entry UUIDs and field names only — never -//! field values, passwords or TOTP secrets. - -use keepass::db::{CustomDataValue, GroupRef}; -use keepass::{Database, DatabaseKey}; -use keepassity_core::kdbx::detect_version; -use serde::Serialize; -use sha2::{Digest, Sha256}; -use std::collections::{BTreeMap, BTreeSet}; -use std::fs::File; -use std::io::Read; - -#[derive(Clone, Debug, Serialize, PartialEq)] -struct FieldInfo { - value: String, - protected: bool, -} - -#[derive(Clone, Debug, Serialize, PartialEq)] -struct AttachmentInfo { - name: String, - size: usize, - sha256: String, -} - -#[derive(Clone, Debug, Serialize, PartialEq)] -struct EntryInfo { - uuid: String, - title: String, - username: String, - password: String, - url: String, - notes: String, - tags: Vec, - fields: BTreeMap, - history: usize, - attachments: Vec, - custom_data_keys: Vec, -} - -#[derive(Clone, Debug, Serialize, PartialEq)] -struct GroupInfo { - uuid: String, - name: String, -} - -#[derive(Clone, Debug, Serialize, PartialEq)] -struct MemoryProtectionInfo { - protect_title: bool, - protect_username: bool, - protect_password: bool, - protect_url: bool, - protect_notes: bool, -} - -#[derive(Clone, Debug, Serialize, Default, PartialEq)] -struct MetaInfo { - database_name: Option, - database_description: Option, - default_username: Option, - memory_protection: Option, - recyclebin_enabled: Option, - history_max_items: Option, - history_max_size: Option, - custom_data: BTreeMap, -} - -#[derive(Clone, Debug, Serialize, Default, PartialEq)] -struct XmlStats { - protected_total: usize, - protected_by_key: BTreeMap, -} - -#[derive(Clone, Debug)] -struct Dump { - bytes: u64, - version: String, - groups: Vec, - entries: Vec, - deleted_objects: Vec, - meta: MetaInfo, - xml: XmlStats, -} - -/// Run `keepassity-cli verify `. -pub fn run(args: &[String], password: &str) -> Result { - let original_path = args - .get(2) - .ok_or_else(|| "missing ".to_string())?; - let modified_path = args - .get(3) - .ok_or_else(|| "missing ".to_string())?; - - let original = dump(original_path, password)?; - let modified = dump(modified_path, password)?; - let expect_title = match ( - crate::arg_value(args, "--expect-title-old"), - crate::arg_value(args, "--expect-title-new"), - ) { - (Some(old), Some(new)) => Some((old, new)), - _ => None, - }; - let allow_empty_standard_fields = args.iter().any(|a| a == "--allow-empty-standard-fields"); - let failures = compare( - &original, - &modified, - expect_title, - allow_empty_standard_fields, - ); - let pass = failures.is_empty(); - for failure in &failures { - println!("FAIL: {failure}"); - } - if pass { - println!("PASS: all compared fields preserved"); - } - let summary = serde_json::json!({ - "pass": pass, - "original_version": original.version, - "modified_version": modified.version, - "original_entries": original.entries.len(), - "modified_entries": modified.entries.len(), - "original_groups": original.groups.len(), - "modified_groups": modified.groups.len(), - "original_attachments": original.entries.iter().map(|e| e.attachments.len()).sum::(), - "modified_attachments": modified.entries.iter().map(|e| e.attachments.len()).sum::(), - "original_deleted_objects": original.deleted_objects.len(), - "modified_deleted_objects": modified.deleted_objects.len(), - "protected_fields": original.xml.protected_total, - "modified_protected_fields": modified.xml.protected_total, - "failures": failures, - }); - println!( - "{}", - serde_json::to_string(&summary).map_err(|e| format!("json: {e}"))? - ); - Ok(if pass { 0 } else { 1 }) -} - -fn sha256_hex(bytes: &[u8]) -> String { - let digest = Sha256::digest(bytes); - let mut out = String::with_capacity(digest.len() * 2); - for byte in digest { - out.push_str(&format!("{byte:02x}")); - } - out -} - -fn detect_path(path: &str) -> Result { - let mut header = [0u8; 12]; - let mut file = File::open(path).map_err(|e| format!("cannot open {path}: {e}"))?; - file.read_exact(&mut header) - .map_err(|e| format!("cannot read header of {path}: {e}"))?; - detect_version(&header) - .map(|v| v.as_str().to_string()) - .map_err(|e| format!("{path}: {e}")) -} - -fn open_db(path: &str, password: &str) -> Result { - let mut file = File::open(path).map_err(|e| format!("cannot open {path}: {e}"))?; - let key = DatabaseKey::new().with_password(password); - Database::open(&mut file, key).map_err(|e| format!("cannot read {path}: {e:?}")) -} - -fn get_xml(path: &str, password: &str) -> Result, String> { - let mut file = File::open(path).map_err(|e| format!("cannot open {path}: {e}"))?; - let key = DatabaseKey::new().with_password(password); - Database::get_xml(&mut file, key).map_err(|e| format!("cannot decrypt {path}: {e:?}")) -} - -fn walk_groups(group: &GroupRef<'_>, out: &mut Vec) { - out.push(GroupInfo { - uuid: group.id().uuid().to_string(), - name: group.name.clone(), - }); - for sub in group.groups() { - walk_groups(&sub, out); - } -} - -fn custom_data_map( - map: &std::collections::HashMap, -) -> BTreeMap { - map.iter() - .map(|(key, item)| { - let value = match &item.value { - Some(CustomDataValue::String(s)) => s.clone(), - Some(CustomDataValue::Binary(b)) => format!("", b.len()), - None => String::new(), - }; - (key.clone(), value) - }) - .collect() -} - -fn dump_meta(db: &Database) -> MetaInfo { - let meta = &db.meta; - MetaInfo { - database_name: meta.database_name.clone(), - database_description: meta.database_description.clone(), - default_username: meta.default_username.clone(), - memory_protection: meta - .memory_protection - .as_ref() - .map(|p| MemoryProtectionInfo { - protect_title: p.protect_title, - protect_username: p.protect_username, - protect_password: p.protect_password, - protect_url: p.protect_url, - protect_notes: p.protect_notes, - }), - recyclebin_enabled: meta.recyclebin_enabled, - history_max_items: meta.history_max_items, - history_max_size: meta.history_max_size, - custom_data: custom_data_map(&meta.custom_data), - } -} - -fn xml_stats(xml: &[u8]) -> XmlStats { - let text = String::from_utf8_lossy(xml); - let mut protected_total = 0usize; - let mut protected_by_key: BTreeMap = BTreeMap::new(); - let mut offset = 0usize; - while let Some(rel) = text[offset..].find("Protected=\"True\"") { - let pos = offset + rel; - protected_total += 1; - if let Some(key_pos) = text[..pos].rfind("") { - let after = &text[key_pos + "".len()..]; - if let Some(end) = after.find("") { - *protected_by_key - .entry(after[..end].to_string()) - .or_insert(0) += 1; - } - } - offset = pos + 1; - } - XmlStats { - protected_total, - protected_by_key, - } -} - -fn dump(path: &str, password: &str) -> Result { - let db = open_db(path, password)?; - let version = detect_path(path)?; - let bytes = std::fs::metadata(path) - .map_err(|e| format!("cannot stat {path}: {e}"))? - .len(); - - let mut groups = Vec::new(); - walk_groups(&db.root(), &mut groups); - groups.sort_by(|a, b| (&a.uuid, &a.name).cmp(&(&b.uuid, &b.name))); - - let mut entries: Vec = Vec::new(); - for entry in db.iter_all_entries() { - let mut fields = BTreeMap::new(); - for (key, value) in entry.fields.iter() { - fields.insert( - key.clone(), - FieldInfo { - value: value.get().clone(), - protected: value.is_protected(), - }, - ); - } - let mut attachments: Vec = entry - .attachments_named() - .map(|(name, att)| { - let data = att.data.get(); - AttachmentInfo { - name: name.to_string(), - size: data.len(), - sha256: sha256_hex(data), - } - }) - .collect(); - attachments.sort_by(|a, b| a.name.cmp(&b.name)); - let mut history = 0usize; - while entry.historical(history).is_some() { - history += 1; - } - let mut custom_data_keys: Vec = entry.custom_data.keys().cloned().collect(); - custom_data_keys.sort(); - entries.push(EntryInfo { - uuid: entry.id().uuid().to_string(), - title: entry.get_title().unwrap_or("").to_string(), - username: entry.get_username().unwrap_or("").to_string(), - password: entry.get_password().unwrap_or("").to_string(), - url: entry.get_url().unwrap_or("").to_string(), - notes: entry.get("Notes").unwrap_or("").to_string(), - tags: { - let mut tags = entry.tags.clone(); - tags.sort(); - tags - }, - fields, - history, - attachments, - custom_data_keys, - }); - } - entries.sort_by(|a, b| a.uuid.cmp(&b.uuid)); - - let mut deleted_objects: Vec = db - .deleted_objects - .keys() - .map(|uuid| uuid.to_string()) - .collect(); - deleted_objects.sort(); - - let xml = xml_stats(&get_xml(path, password)?); - - Ok(Dump { - bytes, - version, - groups, - entries, - deleted_objects, - meta: dump_meta(&db), - xml, - }) -} - -fn compare( - original: &Dump, - output: &Dump, - expect_title: Option<(String, String)>, - allow_empty_standard_fields: bool, -) -> Vec { - let mut failures = Vec::new(); - - let original_groups: BTreeMap<&str, &str> = original - .groups - .iter() - .map(|g| (g.uuid.as_str(), g.name.as_str())) - .collect(); - let output_groups: BTreeMap<&str, &str> = output - .groups - .iter() - .map(|g| (g.uuid.as_str(), g.name.as_str())) - .collect(); - for uuid in original_groups.keys() { - if !output_groups.contains_key(uuid) { - failures.push(format!("group {uuid} missing from output")); - } - } - for uuid in output_groups.keys() { - if !original_groups.contains_key(uuid) { - failures.push(format!("group {uuid} added by output")); - } - } - for (uuid, name) in &original_groups { - if let Some(after) = output_groups.get(uuid) { - if name != after { - failures.push(format!("group {uuid}: name changed")); - } - } - } - - let original_entries: BTreeMap<&str, &EntryInfo> = original - .entries - .iter() - .map(|e| (e.uuid.as_str(), e)) - .collect(); - let output_entries: BTreeMap<&str, &EntryInfo> = output - .entries - .iter() - .map(|e| (e.uuid.as_str(), e)) - .collect(); - for uuid in original_entries.keys() { - if !output_entries.contains_key(uuid) { - failures.push(format!("entry {uuid} missing from output")); - } - } - for uuid in output_entries.keys() { - if !original_entries.contains_key(uuid) { - failures.push(format!("entry {uuid} added by output")); - } - } - - // Work out which entry is allowed to change title: exactly one entry whose - // title went old -> new. All other entries must keep their title unchanged. - let mut title_change_uuid: Option = None; - if let Some((old, new)) = &expect_title { - let changed: Vec<&str> = original - .entries - .iter() - .filter(|before| { - output_entries - .get(before.uuid.as_str()) - .map(|after| &before.title == old && &after.title == new) - .unwrap_or(false) - }) - .map(|e| e.uuid.as_str()) - .collect(); - if changed.len() == 1 { - title_change_uuid = Some(changed[0].to_string()); - } else { - failures.push(format!( - "expected title change not observed exactly once (matches={})", - changed.len() - )); - } - } - - for (uuid, before) in &original_entries { - let Some(after) = output_entries.get(*uuid) else { - continue; - }; - if before.username != after.username { - failures.push(format!("entry {uuid}: username changed")); - } - if before.password != after.password { - failures.push(format!("entry {uuid}: password changed")); - } - if before.url != after.url { - failures.push(format!("entry {uuid}: url changed")); - } - if before.notes != after.notes { - failures.push(format!("entry {uuid}: notes changed")); - } - if before.tags != after.tags { - failures.push(format!("entry {uuid}: tags changed")); - } - if before.history != after.history { - failures.push(format!( - "entry {uuid}: history count {} -> {}", - before.history, after.history - )); - } - if before.attachments != after.attachments { - failures.push(format!("entry {uuid}: attachments changed")); - } - if before.custom_data_keys != after.custom_data_keys { - failures.push(format!("entry {uuid}: custom_data keys changed")); - } - - let title_allowed = match &title_change_uuid { - Some(changed) if changed == uuid => { - if let Some((old, new)) = &expect_title { - before.title == *old && after.title == *new - } else { - before.title == after.title - } - } - _ => before.title == after.title, - }; - if !title_allowed { - failures.push(format!("entry {uuid}: title not as expected")); - } - - let field_keys: BTreeSet<&String> = - before.fields.keys().chain(after.fields.keys()).collect(); - for key in field_keys { - if key == "Title" && title_allowed { - continue; - } - match (before.fields.get(key), after.fields.get(key)) { - (Some(a), Some(b)) => { - if a.value != b.value { - failures.push(format!("entry {uuid}: field {key} value changed")); - } - if a.protected != b.protected { - failures.push(format!("entry {uuid}: field {key} protected flag changed")); - } - } - (Some(_), None) => failures.push(format!("entry {uuid}: field {key} lost")), - (None, Some(b)) => { - // Accepted Q10 deviation: keepassxcr materialises empty - // Notes/URL/UserName fields for legacy entries that omitted - // them. Only allow that exact, semantics-free addition. - let empty_standard = allow_empty_standard_fields - && matches!(key.as_str(), "Notes" | "URL" | "UserName") - && b.value.is_empty(); - if !empty_standard { - failures.push(format!("entry {uuid}: field {key} added")); - } - } - (None, None) => {} - } - } - } - - if original.deleted_objects != output.deleted_objects { - failures.push("deleted_objects changed".to_string()); - } - - let meta_pairs: [(&str, String, String); 7] = [ - ( - "database_name", - format!("{:?}", original.meta.database_name), - format!("{:?}", output.meta.database_name), - ), - ( - "database_description", - format!("{:?}", original.meta.database_description), - format!("{:?}", output.meta.database_description), - ), - ( - "default_username", - format!("{:?}", original.meta.default_username), - format!("{:?}", output.meta.default_username), - ), - ( - "memory_protection", - format!("{:?}", original.meta.memory_protection), - format!("{:?}", output.meta.memory_protection), - ), - ( - "recyclebin_enabled", - format!("{:?}", original.meta.recyclebin_enabled), - format!("{:?}", output.meta.recyclebin_enabled), - ), - ( - "history_max_items", - format!("{:?}", original.meta.history_max_items), - format!("{:?}", output.meta.history_max_items), - ), - ( - "history_max_size", - format!("{:?}", original.meta.history_max_size), - format!("{:?}", output.meta.history_max_size), - ), - ]; - for (name, a, b) in meta_pairs { - if a != b { - failures.push(format!("meta {name} changed")); - } - } - if original.meta.custom_data != output.meta.custom_data { - failures.push("meta custom_data changed".to_string()); - } - - if original.xml.protected_total != output.xml.protected_total - || original.xml.protected_by_key != output.xml.protected_by_key - { - failures.push("protected fields changed".to_string()); - } - - let _ = (original.bytes, output.bytes); - failures -} diff --git a/crates/cli/src/verify/compare.rs b/crates/cli/src/verify/compare.rs new file mode 100644 index 0000000..202fe10 --- /dev/null +++ b/crates/cli/src/verify/compare.rs @@ -0,0 +1,224 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Comparing two dumps and reporting their differences. + +use super::*; + +pub(crate) fn compare( + original: &Dump, + output: &Dump, + expect_title: Option<(String, String)>, + allow_empty_standard_fields: bool, +) -> Vec { + let mut failures = Vec::new(); + + let original_groups: BTreeMap<&str, &str> = original + .groups + .iter() + .map(|g| (g.uuid.as_str(), g.name.as_str())) + .collect(); + let output_groups: BTreeMap<&str, &str> = output + .groups + .iter() + .map(|g| (g.uuid.as_str(), g.name.as_str())) + .collect(); + for uuid in original_groups.keys() { + if !output_groups.contains_key(uuid) { + failures.push(format!("group {uuid} missing from output")); + } + } + for uuid in output_groups.keys() { + if !original_groups.contains_key(uuid) { + failures.push(format!("group {uuid} added by output")); + } + } + for (uuid, name) in &original_groups { + if let Some(after) = output_groups.get(uuid) { + if name != after { + failures.push(format!("group {uuid}: name changed")); + } + } + } + + let original_entries: BTreeMap<&str, &EntryInfo> = original + .entries + .iter() + .map(|e| (e.uuid.as_str(), e)) + .collect(); + let output_entries: BTreeMap<&str, &EntryInfo> = output + .entries + .iter() + .map(|e| (e.uuid.as_str(), e)) + .collect(); + for uuid in original_entries.keys() { + if !output_entries.contains_key(uuid) { + failures.push(format!("entry {uuid} missing from output")); + } + } + for uuid in output_entries.keys() { + if !original_entries.contains_key(uuid) { + failures.push(format!("entry {uuid} added by output")); + } + } + + // Work out which entry is allowed to change title: exactly one entry whose + // title went old -> new. All other entries must keep their title unchanged. + let mut title_change_uuid: Option = None; + if let Some((old, new)) = &expect_title { + let changed: Vec<&str> = original + .entries + .iter() + .filter(|before| { + output_entries + .get(before.uuid.as_str()) + .map(|after| &before.title == old && &after.title == new) + .unwrap_or(false) + }) + .map(|e| e.uuid.as_str()) + .collect(); + if changed.len() == 1 { + title_change_uuid = Some(changed[0].to_string()); + } else { + failures.push(format!( + "expected title change not observed exactly once (matches={})", + changed.len() + )); + } + } + + for (uuid, before) in &original_entries { + let Some(after) = output_entries.get(*uuid) else { + continue; + }; + if before.username != after.username { + failures.push(format!("entry {uuid}: username changed")); + } + if before.password != after.password { + failures.push(format!("entry {uuid}: password changed")); + } + if before.url != after.url { + failures.push(format!("entry {uuid}: url changed")); + } + if before.notes != after.notes { + failures.push(format!("entry {uuid}: notes changed")); + } + if before.tags != after.tags { + failures.push(format!("entry {uuid}: tags changed")); + } + if before.history != after.history { + failures.push(format!( + "entry {uuid}: history count {} -> {}", + before.history, after.history + )); + } + if before.attachments != after.attachments { + failures.push(format!("entry {uuid}: attachments changed")); + } + if before.custom_data_keys != after.custom_data_keys { + failures.push(format!("entry {uuid}: custom_data keys changed")); + } + + let title_allowed = match &title_change_uuid { + Some(changed) if changed == uuid => { + if let Some((old, new)) = &expect_title { + before.title == *old && after.title == *new + } else { + before.title == after.title + } + } + _ => before.title == after.title, + }; + if !title_allowed { + failures.push(format!("entry {uuid}: title not as expected")); + } + + let field_keys: BTreeSet<&String> = + before.fields.keys().chain(after.fields.keys()).collect(); + for key in field_keys { + if key == "Title" && title_allowed { + continue; + } + match (before.fields.get(key), after.fields.get(key)) { + (Some(a), Some(b)) => { + if a.value != b.value { + failures.push(format!("entry {uuid}: field {key} value changed")); + } + if a.protected != b.protected { + failures.push(format!("entry {uuid}: field {key} protected flag changed")); + } + } + (Some(_), None) => failures.push(format!("entry {uuid}: field {key} lost")), + (None, Some(b)) => { + // Accepted Q10 deviation: keepassxcr materialises empty + // Notes/URL/UserName fields for legacy entries that omitted + // them. Only allow that exact, semantics-free addition. + let empty_standard = allow_empty_standard_fields + && matches!(key.as_str(), "Notes" | "URL" | "UserName") + && b.value.is_empty(); + if !empty_standard { + failures.push(format!("entry {uuid}: field {key} added")); + } + } + (None, None) => {} + } + } + } + + if original.deleted_objects != output.deleted_objects { + failures.push("deleted_objects changed".to_string()); + } + + let meta_pairs: [(&str, String, String); 7] = [ + ( + "database_name", + format!("{:?}", original.meta.database_name), + format!("{:?}", output.meta.database_name), + ), + ( + "database_description", + format!("{:?}", original.meta.database_description), + format!("{:?}", output.meta.database_description), + ), + ( + "default_username", + format!("{:?}", original.meta.default_username), + format!("{:?}", output.meta.default_username), + ), + ( + "memory_protection", + format!("{:?}", original.meta.memory_protection), + format!("{:?}", output.meta.memory_protection), + ), + ( + "recyclebin_enabled", + format!("{:?}", original.meta.recyclebin_enabled), + format!("{:?}", output.meta.recyclebin_enabled), + ), + ( + "history_max_items", + format!("{:?}", original.meta.history_max_items), + format!("{:?}", output.meta.history_max_items), + ), + ( + "history_max_size", + format!("{:?}", original.meta.history_max_size), + format!("{:?}", output.meta.history_max_size), + ), + ]; + for (name, a, b) in meta_pairs { + if a != b { + failures.push(format!("meta {name} changed")); + } + } + if original.meta.custom_data != output.meta.custom_data { + failures.push("meta custom_data changed".to_string()); + } + + if original.xml.protected_total != output.xml.protected_total + || original.xml.protected_by_key != output.xml.protected_by_key + { + failures.push("protected fields changed".to_string()); + } + + let _ = (original.bytes, output.bytes); + failures +} diff --git a/crates/cli/src/verify/dump.rs b/crates/cli/src/verify/dump.rs new file mode 100644 index 0000000..ac2ee7b --- /dev/null +++ b/crates/cli/src/verify/dump.rs @@ -0,0 +1,229 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! The canonical model dump: what a database contains, as data. + +use super::*; + +#[derive(Clone, Debug, Serialize, PartialEq)] +pub(crate) struct FieldInfo { + pub(crate) value: String, + pub(crate) protected: bool, +} + +#[derive(Clone, Debug, Serialize, PartialEq)] +pub(crate) struct AttachmentInfo { + pub(crate) name: String, + pub(crate) size: usize, + pub(crate) sha256: String, +} + +#[derive(Clone, Debug, Serialize, PartialEq)] +pub(crate) struct EntryInfo { + pub(crate) uuid: String, + pub(crate) title: String, + pub(crate) username: String, + pub(crate) password: String, + pub(crate) url: String, + pub(crate) notes: String, + pub(crate) tags: Vec, + pub(crate) fields: BTreeMap, + pub(crate) history: usize, + pub(crate) attachments: Vec, + pub(crate) custom_data_keys: Vec, +} + +#[derive(Clone, Debug, Serialize, PartialEq)] +pub(crate) struct GroupInfo { + pub(crate) uuid: String, + pub(crate) name: String, +} + +#[derive(Clone, Debug, Serialize, PartialEq)] +pub(crate) struct MemoryProtectionInfo { + pub(crate) protect_title: bool, + pub(crate) protect_username: bool, + pub(crate) protect_password: bool, + pub(crate) protect_url: bool, + pub(crate) protect_notes: bool, +} + +#[derive(Clone, Debug, Serialize, Default, PartialEq)] +pub(crate) struct MetaInfo { + pub(crate) database_name: Option, + pub(crate) database_description: Option, + pub(crate) default_username: Option, + pub(crate) memory_protection: Option, + pub(crate) recyclebin_enabled: Option, + pub(crate) history_max_items: Option, + pub(crate) history_max_size: Option, + pub(crate) custom_data: BTreeMap, +} + +#[derive(Clone, Debug, Serialize, Default, PartialEq)] +pub(crate) struct XmlStats { + pub(crate) protected_total: usize, + pub(crate) protected_by_key: BTreeMap, +} + +#[derive(Clone, Debug)] +pub(crate) struct Dump { + pub(crate) bytes: u64, + pub(crate) version: String, + pub(crate) groups: Vec, + pub(crate) entries: Vec, + pub(crate) deleted_objects: Vec, + pub(crate) meta: MetaInfo, + pub(crate) xml: XmlStats, +} + +pub(crate) fn walk_groups(group: &GroupRef<'_>, out: &mut Vec) { + out.push(GroupInfo { + uuid: group.id().uuid().to_string(), + name: group.name.clone(), + }); + for sub in group.groups() { + walk_groups(&sub, out); + } +} + +pub(crate) fn custom_data_map( + map: &std::collections::HashMap, +) -> BTreeMap { + map.iter() + .map(|(key, item)| { + let value = match &item.value { + Some(CustomDataValue::String(s)) => s.clone(), + Some(CustomDataValue::Binary(b)) => format!("", b.len()), + None => String::new(), + }; + (key.clone(), value) + }) + .collect() +} + +pub(crate) fn dump_meta(db: &Database) -> MetaInfo { + let meta = &db.meta; + MetaInfo { + database_name: meta.database_name.clone(), + database_description: meta.database_description.clone(), + default_username: meta.default_username.clone(), + memory_protection: meta + .memory_protection + .as_ref() + .map(|p| MemoryProtectionInfo { + protect_title: p.protect_title, + protect_username: p.protect_username, + protect_password: p.protect_password, + protect_url: p.protect_url, + protect_notes: p.protect_notes, + }), + recyclebin_enabled: meta.recyclebin_enabled, + history_max_items: meta.history_max_items, + history_max_size: meta.history_max_size, + custom_data: custom_data_map(&meta.custom_data), + } +} + +pub(crate) fn xml_stats(xml: &[u8]) -> XmlStats { + let text = String::from_utf8_lossy(xml); + let mut protected_total = 0usize; + let mut protected_by_key: BTreeMap = BTreeMap::new(); + let mut offset = 0usize; + while let Some(rel) = text[offset..].find("Protected=\"True\"") { + let pos = offset + rel; + protected_total += 1; + if let Some(key_pos) = text[..pos].rfind("") { + let after = &text[key_pos + "".len()..]; + if let Some(end) = after.find("") { + *protected_by_key + .entry(after[..end].to_string()) + .or_insert(0) += 1; + } + } + offset = pos + 1; + } + XmlStats { + protected_total, + protected_by_key, + } +} + +pub(crate) fn dump(path: &str, password: &str) -> Result { + let db = open_db(path, password)?; + let version = detect_path(path)?; + let bytes = std::fs::metadata(path) + .map_err(|e| format!("cannot stat {path}: {e}"))? + .len(); + + let mut groups = Vec::new(); + walk_groups(&db.root(), &mut groups); + groups.sort_by(|a, b| (&a.uuid, &a.name).cmp(&(&b.uuid, &b.name))); + + let mut entries: Vec = Vec::new(); + for entry in db.iter_all_entries() { + let mut fields = BTreeMap::new(); + for (key, value) in entry.fields.iter() { + fields.insert( + key.clone(), + FieldInfo { + value: value.get().clone(), + protected: value.is_protected(), + }, + ); + } + let mut attachments: Vec = entry + .attachments_named() + .map(|(name, att)| { + let data = att.data.get(); + AttachmentInfo { + name: name.to_string(), + size: data.len(), + sha256: sha256_hex(data), + } + }) + .collect(); + attachments.sort_by(|a, b| a.name.cmp(&b.name)); + let mut history = 0usize; + while entry.historical(history).is_some() { + history += 1; + } + let mut custom_data_keys: Vec = entry.custom_data.keys().cloned().collect(); + custom_data_keys.sort(); + entries.push(EntryInfo { + uuid: entry.id().uuid().to_string(), + title: entry.get_title().unwrap_or("").to_string(), + username: entry.get_username().unwrap_or("").to_string(), + password: entry.get_password().unwrap_or("").to_string(), + url: entry.get_url().unwrap_or("").to_string(), + notes: entry.get("Notes").unwrap_or("").to_string(), + tags: { + let mut tags = entry.tags.clone(); + tags.sort(); + tags + }, + fields, + history, + attachments, + custom_data_keys, + }); + } + entries.sort_by(|a, b| a.uuid.cmp(&b.uuid)); + + let mut deleted_objects: Vec = db + .deleted_objects + .keys() + .map(|uuid| uuid.to_string()) + .collect(); + deleted_objects.sort(); + + let xml = xml_stats(&get_xml(path, password)?); + + Ok(Dump { + bytes, + version, + groups, + entries, + deleted_objects, + meta: dump_meta(&db), + xml, + }) +} diff --git a/crates/cli/src/verify/io.rs b/crates/cli/src/verify/io.rs new file mode 100644 index 0000000..4bf27d4 --- /dev/null +++ b/crates/cli/src/verify/io.rs @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Reading a database file and hashing its bytes. + +use super::*; + +pub(crate) fn sha256_hex(bytes: &[u8]) -> String { + let digest = Sha256::digest(bytes); + let mut out = String::with_capacity(digest.len() * 2); + for byte in digest { + out.push_str(&format!("{byte:02x}")); + } + out +} + +pub(crate) fn detect_path(path: &str) -> Result { + let mut header = [0u8; 12]; + let mut file = File::open(path).map_err(|e| format!("cannot open {path}: {e}"))?; + file.read_exact(&mut header) + .map_err(|e| format!("cannot read header of {path}: {e}"))?; + detect_version(&header) + .map(|v| v.as_str().to_string()) + .map_err(|e| format!("{path}: {e}")) +} + +pub(crate) fn open_db(path: &str, password: &str) -> Result { + let mut file = File::open(path).map_err(|e| format!("cannot open {path}: {e}"))?; + let key = DatabaseKey::new().with_password(password); + Database::open(&mut file, key).map_err(|e| format!("cannot read {path}: {e:?}")) +} + +pub(crate) fn get_xml(path: &str, password: &str) -> Result, String> { + let mut file = File::open(path).map_err(|e| format!("cannot open {path}: {e}"))?; + let key = DatabaseKey::new().with_password(password); + Database::get_xml(&mut file, key).map_err(|e| format!("cannot decrypt {path}: {e:?}")) +} diff --git a/crates/cli/src/verify/mod.rs b/crates/cli/src/verify/mod.rs new file mode 100644 index 0000000..81959a7 --- /dev/null +++ b/crates/cli/src/verify/mod.rs @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! `verify`: independent structural comparison of two KDBX files. +//! +//! Reading uses the project's established read path (`keepass 0.17`). Nothing +//! is written; failure messages contain entry UUIDs and field names only — never +//! field values, passwords or TOTP secrets. + +use keepass::db::{CustomDataValue, GroupRef}; +use keepass::{Database, DatabaseKey}; +use keepassity_core::kdbx::detect_version; +use serde::Serialize; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet}; +use std::fs::File; +use std::io::Read; + +/// Run `keepassity-cli verify `. +pub fn run(args: &[String], password: &str) -> Result { + let original_path = args + .get(2) + .ok_or_else(|| "missing ".to_string())?; + let modified_path = args + .get(3) + .ok_or_else(|| "missing ".to_string())?; + + let original = dump(original_path, password)?; + let modified = dump(modified_path, password)?; + let expect_title = match ( + crate::arg_value(args, "--expect-title-old"), + crate::arg_value(args, "--expect-title-new"), + ) { + (Some(old), Some(new)) => Some((old, new)), + _ => None, + }; + let allow_empty_standard_fields = args.iter().any(|a| a == "--allow-empty-standard-fields"); + let failures = compare( + &original, + &modified, + expect_title, + allow_empty_standard_fields, + ); + let pass = failures.is_empty(); + for failure in &failures { + println!("FAIL: {failure}"); + } + if pass { + println!("PASS: all compared fields preserved"); + } + let summary = serde_json::json!({ + "pass": pass, + "original_version": original.version, + "modified_version": modified.version, + "original_entries": original.entries.len(), + "modified_entries": modified.entries.len(), + "original_groups": original.groups.len(), + "modified_groups": modified.groups.len(), + "original_attachments": original.entries.iter().map(|e| e.attachments.len()).sum::(), + "modified_attachments": modified.entries.iter().map(|e| e.attachments.len()).sum::(), + "original_deleted_objects": original.deleted_objects.len(), + "modified_deleted_objects": modified.deleted_objects.len(), + "protected_fields": original.xml.protected_total, + "modified_protected_fields": modified.xml.protected_total, + "failures": failures, + }); + println!( + "{}", + serde_json::to_string(&summary).map_err(|e| format!("json: {e}"))? + ); + Ok(if pass { 0 } else { 1 }) +} + +mod compare; +mod dump; +mod io; + +use compare::*; +use dump::*; +use io::*; diff --git a/crates/core/src/dto/entry.rs b/crates/core/src/dto/entry.rs new file mode 100644 index 0000000..1784592 --- /dev/null +++ b/crates/core/src/dto/entry.rs @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Entry payloads: summaries, the full record and its custom fields. + +use super::*; + +/// Summary row used by `list_entries`/`search`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EntrySummary { + /// Entry UUID (32 hex). + pub uuid: String, + /// Title. + pub title: String, + /// Username (may be empty). + pub username: String, + /// URL (may be empty). + pub url: String, + /// Parent group UUID (32 hex). + pub group_uuid: String, + /// Any TOTP field present. + pub has_totp: bool, + /// Last modification as Unix seconds when parseable. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub modified_unix: Option, +} + +impl EntrySummary { + /// Build a summary from a model entry. + pub fn from_model(entry: &Entry, group_uuid: Uuid) -> Self { + Self { + uuid: entry.uuid.to_hex(), + title: entry.field("Title").unwrap_or("").to_string(), + username: entry.field("UserName").unwrap_or("").to_string(), + url: entry.field("URL").unwrap_or("").to_string(), + group_uuid: group_uuid.to_hex(), + has_totp: entry.has_totp(), + modified_unix: entry.times.modified_unix(), + } + } +} + +/// Times DTO (Unix seconds). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TimesDto { + /// Creation time. + pub created_unix: i64, + /// Last modification time. + pub modified_unix: i64, + /// Last access time. + pub accessed_unix: i64, + /// Expiry time (`null` when the entry does not expire). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub expires_unix: Option, +} + +impl TimesDto { + /// Build from the model times block. + pub fn from_times(times: &Times) -> Self { + Self { + created_unix: times.created_unix().unwrap_or(0), + modified_unix: times.modified_unix().unwrap_or(0), + accessed_unix: times.accessed_unix().unwrap_or(0), + expires_unix: times.expires_unix(), + } + } +} + +/// One custom field. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct CustomField { + /// Field key. + pub key: String, + /// Field value. + pub value: String, + /// `Protected="True"` flag. + pub protected: bool, +} + +/// Full entry DTO (`get_entry`). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EntryFull { + /// Entry UUID. + pub uuid: String, + /// Parent group UUID. + pub group_uuid: String, + /// Title. + pub title: String, + /// Username. + pub username: String, + /// URL. + pub url: String, + /// Any TOTP field present. + pub has_totp: bool, + /// Last modification as Unix seconds. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub modified_unix: Option, + /// SECRET: password value; never log. + pub password_secret: String, + /// Notes. + pub notes: String, + /// Tags. + pub tags: Vec, + /// Non-standard fields. + pub custom_fields: Vec, + /// Numeric icon id. + pub icon: u32, + /// Times. + pub times: TimesDto, + /// Number of history entries. + pub history_count: usize, + /// TOTP configuration (filled in M1-05/M1-06). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub totp: Option, +} + +impl EntryFull { + /// Build the full DTO from a model entry (TOTP config is filled later). + pub fn from_model(entry: &Entry, group_uuid: Uuid) -> Self { + let standard = ["Title", "UserName", "Password", "URL", "Notes"]; + let custom_fields = entry + .strings + .iter() + .filter(|field| !standard.contains(&field.key.as_str())) + .map(|field| CustomField { + key: field.key.clone(), + value: field.value.clone(), + protected: field.protected, + }) + .collect(); + Self { + uuid: entry.uuid.to_hex(), + group_uuid: group_uuid.to_hex(), + title: entry.field("Title").unwrap_or("").to_string(), + username: entry.field("UserName").unwrap_or("").to_string(), + url: entry.field("URL").unwrap_or("").to_string(), + has_totp: entry.has_totp(), + modified_unix: entry.times.modified_unix(), + password_secret: entry.field("Password").unwrap_or("").to_string(), + notes: entry.field("Notes").unwrap_or("").to_string(), + tags: entry.tags.clone(), + custom_fields, + icon: entry.icon_id, + times: TimesDto::from_times(&entry.times), + history_count: entry.history.len(), + totp: None, + } + } +} diff --git a/crates/core/src/dto/error.rs b/crates/core/src/dto/error.rs new file mode 100644 index 0000000..99b7794 --- /dev/null +++ b/crates/core/src/dto/error.rs @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! The wire error shape and its stable codes. + +use super::*; + +/// Error code enum (FFI `code`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum ErrorCode { + /// Wrong password/key. + BadPassword, + /// HMAC/format corruption. + CorruptDatabase, + /// Unsupported KDBX version/feature. + UnsupportedFormat, + /// Local file IO failure. + IoError, + /// Network failure. + NetworkError, + /// Sync conflict. + Conflict, + /// Object not found. + NotFound, + /// Bad argument. + InvalidArgument, + /// Database locked. + Locked, + /// API version mismatch. + VersionMismatch, + /// Internal inconsistency. + Internal, +} + +/// Error DTO returned by FFI/CLI. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct DtoError { + /// Error code. + pub code: ErrorCode, + /// Human-readable message (redacted). + pub message: String, + /// Whether a retry may help (sync). + pub retryable: bool, + /// Optional diagnostic detail (redacted). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub detail: Option, +} diff --git a/crates/core/src/dto/mod.rs b/crates/core/src/dto/mod.rs index 39a5a9a..02c4494 100644 --- a/crates/core/src/dto/mod.rs +++ b/crates/core/src/dto/mod.rs @@ -29,380 +29,6 @@ use crate::model::{xml_datetime_to_unix, Entry, Group, Times, Uuid}; use serde::{Deserialize, Serialize}; -/// Summary row used by `list_entries`/`search`. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct EntrySummary { - /// Entry UUID (32 hex). - pub uuid: String, - /// Title. - pub title: String, - /// Username (may be empty). - pub username: String, - /// URL (may be empty). - pub url: String, - /// Parent group UUID (32 hex). - pub group_uuid: String, - /// Any TOTP field present. - pub has_totp: bool, - /// Last modification as Unix seconds when parseable. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub modified_unix: Option, -} - -impl EntrySummary { - /// Build a summary from a model entry. - pub fn from_model(entry: &Entry, group_uuid: Uuid) -> Self { - Self { - uuid: entry.uuid.to_hex(), - title: entry.field("Title").unwrap_or("").to_string(), - username: entry.field("UserName").unwrap_or("").to_string(), - url: entry.field("URL").unwrap_or("").to_string(), - group_uuid: group_uuid.to_hex(), - has_totp: entry.has_totp(), - modified_unix: entry.times.modified_unix(), - } - } -} - -/// Times DTO (Unix seconds). -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct TimesDto { - /// Creation time. - pub created_unix: i64, - /// Last modification time. - pub modified_unix: i64, - /// Last access time. - pub accessed_unix: i64, - /// Expiry time (`null` when the entry does not expire). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub expires_unix: Option, -} - -impl TimesDto { - /// Build from the model times block. - pub fn from_times(times: &Times) -> Self { - Self { - created_unix: times.created_unix().unwrap_or(0), - modified_unix: times.modified_unix().unwrap_or(0), - accessed_unix: times.accessed_unix().unwrap_or(0), - expires_unix: times.expires_unix(), - } - } -} - -/// One custom field. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct CustomField { - /// Field key. - pub key: String, - /// Field value. - pub value: String, - /// `Protected="True"` flag. - pub protected: bool, -} - -/// Full entry DTO (`get_entry`). -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct EntryFull { - /// Entry UUID. - pub uuid: String, - /// Parent group UUID. - pub group_uuid: String, - /// Title. - pub title: String, - /// Username. - pub username: String, - /// URL. - pub url: String, - /// Any TOTP field present. - pub has_totp: bool, - /// Last modification as Unix seconds. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub modified_unix: Option, - /// SECRET: password value; never log. - pub password_secret: String, - /// Notes. - pub notes: String, - /// Tags. - pub tags: Vec, - /// Non-standard fields. - pub custom_fields: Vec, - /// Numeric icon id. - pub icon: u32, - /// Times. - pub times: TimesDto, - /// Number of history entries. - pub history_count: usize, - /// TOTP configuration (filled in M1-05/M1-06). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub totp: Option, -} - -impl EntryFull { - /// Build the full DTO from a model entry (TOTP config is filled later). - pub fn from_model(entry: &Entry, group_uuid: Uuid) -> Self { - let standard = ["Title", "UserName", "Password", "URL", "Notes"]; - let custom_fields = entry - .strings - .iter() - .filter(|field| !standard.contains(&field.key.as_str())) - .map(|field| CustomField { - key: field.key.clone(), - value: field.value.clone(), - protected: field.protected, - }) - .collect(); - Self { - uuid: entry.uuid.to_hex(), - group_uuid: group_uuid.to_hex(), - title: entry.field("Title").unwrap_or("").to_string(), - username: entry.field("UserName").unwrap_or("").to_string(), - url: entry.field("URL").unwrap_or("").to_string(), - has_totp: entry.has_totp(), - modified_unix: entry.times.modified_unix(), - password_secret: entry.field("Password").unwrap_or("").to_string(), - notes: entry.field("Notes").unwrap_or("").to_string(), - tags: entry.tags.clone(), - custom_fields, - icon: entry.icon_id, - times: TimesDto::from_times(&entry.times), - history_count: entry.history.len(), - totp: None, - } - } -} - -/// TOTP hash algorithm. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "UPPERCASE")] -pub enum TotpAlgorithm { - /// HMAC-SHA1. - Sha1, - /// HMAC-SHA256. - Sha256, - /// HMAC-SHA512. - Sha512, -} - -/// TOTP encoder flavor. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum TotpEncoder { - /// Standard TOTP. - Totp, - /// Steam alphabet. - Steam, -} - -/// TOTP configuration DTO. -#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct TotpConfig { - /// SECRET: Base32 seed; never log. - pub secret_base32: String, - /// Issuer (optional). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub issuer: Option, - /// Account name (optional). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub account: Option, - /// Hash algorithm. - pub algorithm: TotpAlgorithm, - /// Code digits (6 or 8). - pub digits: u32, - /// Period in seconds. - pub period: u32, - /// Encoder flavor. - pub encoder: TotpEncoder, - /// Steam/counter value (optional). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub counter: Option, -} - -impl std::fmt::Debug for TotpConfig { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("TotpConfig") - .field("secret_base32", &"") - .field("issuer", &self.issuer) - .field("account", &self.account) - .field("algorithm", &self.algorithm) - .field("digits", &self.digits) - .field("period", &self.period) - .field("encoder", &self.encoder) - .field("counter", &self.counter) - .finish() - } -} - -/// TOTP code DTO. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct TotpCode { - /// Current code. - pub code: String, - /// Seconds until the next code. - pub remaining: u32, - /// Period in seconds. - pub period: u32, - /// Digits. - pub digits: u32, - /// Algorithm name (e.g. `SHA1`). - pub algorithm: String, - /// Issuer. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub issuer: Option, - /// Account. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub account: Option, - /// Large clock skew warning. - pub skew_warning: bool, -} - -/// Remote metadata reliability. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum Reliability { - /// Full ETag/metadata available. - Full, - /// Degraded (mtime/size/hash only). - Degraded, -} - -/// Remote metadata used by `sync_decide`. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct SyncRemoteMeta { - /// ETag, if the server provides one. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub etag: Option, - /// Remote byte size. - pub size: u64, - /// Remote modified time. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub modified_unix: Option, - /// Reliability of the metadata. - pub reliability: Reliability, -} - -/// Sync decision action. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum SyncActionKind { - /// No action. - UpToDate, - /// Upload local changes. - Upload, - /// Download remote changes. - Download, - /// Download and merge. - DownloadAndMerge, - /// Conflict: needs a three-way choice. - Conflict, - /// Offline (defer). - Offline, -} - -/// `sync_decide` result. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct SyncAction { - /// Action to take. - pub action: SyncActionKind, - /// Human-readable reason. - pub reason: String, - /// Degraded (no ETag) decision. - pub degraded: bool, -} - -/// Kind of conflict item. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum ConflictKind { - /// Entry conflict. - Entry, - /// Group conflict. - Group, -} - -/// One conflict item. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct ConflictItem { - /// UUID of the conflicting object. - pub uuid: String, - /// Entry/group. - pub kind: ConflictKind, - /// Local modification time. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub local_modified_unix: Option, - /// Remote modification time. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub remote_modified_unix: Option, - /// Conflicting field names. - pub fields: Vec, -} - -impl From<&crate::merge::MergeConflict> for ConflictItem { - fn from(conflict: &crate::merge::MergeConflict) -> Self { - Self { - uuid: conflict.uuid.to_hex(), - kind: match conflict.kind { - crate::merge::ConflictKind::Entry => ConflictKind::Entry, - crate::merge::ConflictKind::Group => ConflictKind::Group, - }, - local_modified_unix: xml_datetime_to_unix(&conflict.local_modified), - remote_modified_unix: xml_datetime_to_unix(&conflict.remote_modified), - fields: conflict.fields.clone(), - } - } -} - -/// Backup record. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct BackupInfo { - /// Backup file path (platform-provided). - pub path: String, - /// Size in bytes. - pub size: u64, - /// Creation time. - pub created_unix: i64, -} - -/// Error code enum (FFI `code`). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum ErrorCode { - /// Wrong password/key. - BadPassword, - /// HMAC/format corruption. - CorruptDatabase, - /// Unsupported KDBX version/feature. - UnsupportedFormat, - /// Local file IO failure. - IoError, - /// Network failure. - NetworkError, - /// Sync conflict. - Conflict, - /// Object not found. - NotFound, - /// Bad argument. - InvalidArgument, - /// Database locked. - Locked, - /// API version mismatch. - VersionMismatch, - /// Internal inconsistency. - Internal, -} - -/// Error DTO returned by FFI/CLI. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct DtoError { - /// Error code. - pub code: ErrorCode, - /// Human-readable message (redacted). - pub message: String, - /// Whether a retry may help (sync). - pub retryable: bool, - /// Optional diagnostic detail (redacted). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub detail: Option, -} - /// Build the group UUID string for DTOs. pub fn group_uuid_string(group: &Group) -> String { group.uuid.to_hex() @@ -557,3 +183,13 @@ mod tests { assert!(!json.contains("remote_modified_unix")); } } + +mod entry; +mod error; +mod sync; +mod totp; + +pub use entry::*; +pub use error::*; +pub use sync::*; +pub use totp::*; diff --git a/crates/core/src/dto/sync.rs b/crates/core/src/dto/sync.rs new file mode 100644 index 0000000..b140c7f --- /dev/null +++ b/crates/core/src/dto/sync.rs @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Sync payloads: remote metadata, the decision, conflicts and backups. + +use super::*; + +/// Remote metadata reliability. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Reliability { + /// Full ETag/metadata available. + Full, + /// Degraded (mtime/size/hash only). + Degraded, +} + +/// Remote metadata used by `sync_decide`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SyncRemoteMeta { + /// ETag, if the server provides one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub etag: Option, + /// Remote byte size. + pub size: u64, + /// Remote modified time. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub modified_unix: Option, + /// Reliability of the metadata. + pub reliability: Reliability, +} + +/// Sync decision action. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum SyncActionKind { + /// No action. + UpToDate, + /// Upload local changes. + Upload, + /// Download remote changes. + Download, + /// Download and merge. + DownloadAndMerge, + /// Conflict: needs a three-way choice. + Conflict, + /// Offline (defer). + Offline, +} + +/// `sync_decide` result. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SyncAction { + /// Action to take. + pub action: SyncActionKind, + /// Human-readable reason. + pub reason: String, + /// Degraded (no ETag) decision. + pub degraded: bool, +} + +/// Kind of conflict item. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ConflictKind { + /// Entry conflict. + Entry, + /// Group conflict. + Group, +} + +/// One conflict item. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ConflictItem { + /// UUID of the conflicting object. + pub uuid: String, + /// Entry/group. + pub kind: ConflictKind, + /// Local modification time. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub local_modified_unix: Option, + /// Remote modification time. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub remote_modified_unix: Option, + /// Conflicting field names. + pub fields: Vec, +} + +impl From<&crate::merge::MergeConflict> for ConflictItem { + fn from(conflict: &crate::merge::MergeConflict) -> Self { + Self { + uuid: conflict.uuid.to_hex(), + kind: match conflict.kind { + crate::merge::ConflictKind::Entry => ConflictKind::Entry, + crate::merge::ConflictKind::Group => ConflictKind::Group, + }, + local_modified_unix: xml_datetime_to_unix(&conflict.local_modified), + remote_modified_unix: xml_datetime_to_unix(&conflict.remote_modified), + fields: conflict.fields.clone(), + } + } +} + +/// Backup record. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct BackupInfo { + /// Backup file path (platform-provided). + pub path: String, + /// Size in bytes. + pub size: u64, + /// Creation time. + pub created_unix: i64, +} diff --git a/crates/core/src/dto/totp.rs b/crates/core/src/dto/totp.rs new file mode 100644 index 0000000..3a39e19 --- /dev/null +++ b/crates/core/src/dto/totp.rs @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! TOTP payloads: the wire config and the generated code. + +use super::*; + +/// TOTP hash algorithm. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum TotpAlgorithm { + /// HMAC-SHA1. + Sha1, + /// HMAC-SHA256. + Sha256, + /// HMAC-SHA512. + Sha512, +} + +/// TOTP encoder flavor. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum TotpEncoder { + /// Standard TOTP. + Totp, + /// Steam alphabet. + Steam, +} + +/// TOTP configuration DTO. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct TotpConfig { + /// SECRET: Base32 seed; never log. + pub secret_base32: String, + /// Issuer (optional). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub issuer: Option, + /// Account name (optional). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub account: Option, + /// Hash algorithm. + pub algorithm: TotpAlgorithm, + /// Code digits (6 or 8). + pub digits: u32, + /// Period in seconds. + pub period: u32, + /// Encoder flavor. + pub encoder: TotpEncoder, + /// Steam/counter value (optional). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub counter: Option, +} + +impl std::fmt::Debug for TotpConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TotpConfig") + .field("secret_base32", &"") + .field("issuer", &self.issuer) + .field("account", &self.account) + .field("algorithm", &self.algorithm) + .field("digits", &self.digits) + .field("period", &self.period) + .field("encoder", &self.encoder) + .field("counter", &self.counter) + .finish() + } +} + +/// TOTP code DTO. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TotpCode { + /// Current code. + pub code: String, + /// Seconds until the next code. + pub remaining: u32, + /// Period in seconds. + pub period: u32, + /// Digits. + pub digits: u32, + /// Algorithm name (e.g. `SHA1`). + pub algorithm: String, + /// Issuer. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub issuer: Option, + /// Account. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub account: Option, + /// Large clock skew warning. + pub skew_warning: bool, +} diff --git a/crates/core/src/kdbx/reader.rs b/crates/core/src/kdbx/reader.rs deleted file mode 100644 index 0d7c523..0000000 --- a/crates/core/src/kdbx/reader.rs +++ /dev/null @@ -1,711 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-or-later -//! KDBX reader: decrypt a KDBX 3.1/4.0/4.1 byte buffer and map it onto the -//! core model. -//! -//! The established `keepass` crate (MIT) performs decryption and KDF work; this -//! module adds the mapping to our model. It performs **no file IO** — callers -//! pass the file bytes. The raw decrypted XML is retained (not serialized) so -//! that unmapped/unknown data is not lost; canonical dumps only expose its -//! SHA-256. - -use crate::kdbx::{detect_version, KdbxVersion}; -use crate::model::{Association, AutoType, Binary, CustomData, CustomDataItem, CustomDataValue}; -use crate::model::{Database, DeletedObject, Entry, Group, MemoryProtection, Meta, StringField}; -use crate::model::{Times, Uuid}; -use keepass::db::{ - AutoType as KpAutoType, CustomDataItem as KpCustomDataItem, - CustomDataValue as KpCustomDataValue, DataTransferObfuscation, Icon, Times as KpTimes, -}; -use keepass::{Database as KpDatabase, DatabaseKey}; -use sha2::{Digest, Sha256}; -use std::collections::BTreeMap; -use std::fmt; -use std::io::Cursor; - -/// Error returned by the KDBX reader. -#[derive(Debug)] -pub enum KdbxReadError { - /// Wrong password/key (or a key-like failure). - BadPassword, - /// Corrupt/truncated data, bad HMAC, or unparsable content. - Corrupt(String), - /// Unsupported KDBX version or format feature. - Unsupported(String), - /// Header is missing/unknown. - Header(String), -} - -impl fmt::Display for KdbxReadError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::BadPassword => write!(f, "bad password or key (database could not be decrypted)"), - Self::Corrupt(message) => write!(f, "corrupt KDBX database: {message}"), - Self::Unsupported(message) => write!(f, "unsupported KDBX database: {message}"), - Self::Header(message) => write!(f, "invalid KDBX header: {message}"), - } - } -} - -impl std::error::Error for KdbxReadError {} - -fn classify_open_error(error: &impl fmt::Debug) -> KdbxReadError { - let raw = format!("{error:?}"); - if raw.contains("IncorrectKey") || raw.contains("EmptyKey") { - KdbxReadError::BadPassword - } else if raw.contains("UnsupportedVersion") || raw.contains("VersionParse") { - KdbxReadError::Unsupported(raw) - } else if raw.contains("UnexpectedEof") { - KdbxReadError::Corrupt("unexpected end of file".to_string()) - } else { - KdbxReadError::Corrupt(raw) - } -} - -/// Run one upstream `keepass` reader call and turn a panic into a parse error. -/// -/// The upstream `keepass` crate (0.17) panics instead of returning an error for -/// a few malformed header shapes (for example a variant dictionary whose length -/// field points past the end of the buffer: `byteorder::read_u64` indexes out of -/// bounds). A KDBX file is untrusted input - it arrives from WebDAV, a shared -/// folder or the file manager - so a malformed file must surface as a normal -/// read error, not abort the application or the fuzzer. The panic message -/// carries no secret material; it is dropped here and the reason is reported as -/// "malformed header" instead. -fn guard_keepass( - call: impl FnOnce() -> Result, -) -> Result { - match std::panic::catch_unwind(std::panic::AssertUnwindSafe(call)) { - Ok(Ok(value)) => Ok(value), - Ok(Err(error)) => Err(classify_open_error(&error)), - Err(_) => Err(KdbxReadError::Corrupt( - "malformed KDBX header (the upstream reader panicked; file rejected)".to_string(), - )), - } -} - -/// Upper bounds for the key-derivation work a KDBX file may ask for. -/// -/// The header is untrusted input: it can name arbitrary KDF parameters, and the -/// reader would otherwise spend unbounded time (or memory) deriving a key from a -/// hostile file before even noticing a wrong password. The daily fuzzing job -/// found exactly that shape (a KDBX 3.1 header with ~2e18 AES-KDF rounds made the -/// reader run for minutes). The limits are far above real-world databases - the -/// writer's default is 128 MiB / 6 iterations / 4 lanes, about 0.7 s - and only -/// reject requests that are clearly meant to exhaust the machine. -const MAX_AES_KDF_ROUNDS: u64 = 10_000_000; -const MAX_ARGON2_MEMORY_BYTES: u64 = 2 * 1024 * 1024 * 1024; -const MAX_ARGON2_ITERATIONS: u64 = 64; -const MAX_ARGON2_PARALLELISM: u32 = 16; -/// `memory (MiB) * iterations` bound; about eight times the write default. -const MAX_ARGON2_WORK_MIB_ITERATIONS: u64 = 6_144; - -const UUID_AES_KDF: [u8; 16] = [ - 0xC9, 0xD9, 0xF3, 0x9A, 0x62, 0x8A, 0x44, 0x60, 0xBF, 0x74, 0x0D, 0x08, 0xC1, 0x8A, 0x4F, 0xEA, -]; -const UUID_ARGON2D: [u8; 16] = [ - 0xEF, 0x63, 0x6D, 0xDF, 0x8C, 0x29, 0x44, 0x4B, 0x91, 0xF7, 0xA9, 0xA4, 0x03, 0xE3, 0x0A, 0x0C, -]; -const UUID_ARGON2ID: [u8; 16] = [ - 0x9E, 0x29, 0x8B, 0x19, 0x56, 0xDB, 0x47, 0x73, 0xB2, 0x3D, 0xFC, 0x3E, 0xC6, 0xF0, 0xA1, 0xE6, -]; - -fn extreme_kdf_error(detail: impl fmt::Display) -> KdbxReadError { - KdbxReadError::Unsupported(format!( - "the database asks for an extreme {detail} (opening it would take a very long \ - time); open it in KeePass and re-save it with normal KDF settings" - )) -} - -fn read_le_u16(bytes: &[u8], offset: usize) -> Option { - Some(u16::from_le_bytes( - bytes.get(offset..offset + 2)?.try_into().ok()?, - )) -} - -fn read_le_u32(bytes: &[u8], offset: usize) -> Option { - Some(u32::from_le_bytes( - bytes.get(offset..offset + 4)?.try_into().ok()?, - )) -} - -fn read_le_u64(bytes: &[u8], offset: usize) -> Option { - Some(u64::from_le_bytes( - bytes.get(offset..offset + 8)?.try_into().ok()?, - )) -} - -/// Rejects headers whose KDF parameters would make key derivation take far too -/// long. Called before the third-party reader runs; a file that fails here is a -/// normal read error (never a panic and never a multi-minute stall). -pub(crate) fn validate_kdf_cost(bytes: &[u8], version: KdbxVersion) -> Result<(), KdbxReadError> { - match version { - KdbxVersion::V3_1 => validate_kdbx3_kdf(bytes), - KdbxVersion::V4_0 | KdbxVersion::V4_1 => validate_kdbx4_kdf(bytes), - } -} - -fn validate_kdbx3_kdf(bytes: &[u8]) -> Result<(), KdbxReadError> { - let mut offset = 12usize; - loop { - let field = match bytes.get(offset) { - Some(value) => *value, - None => return Ok(()), - }; - if field == 0 { - return Ok(()); - } - let Some(length) = read_le_u16(bytes, offset + 1) else { - return Ok(()); - }; - let start = offset + 3; - let end = start + length as usize; - let Some(payload) = bytes.get(start..end) else { - return Ok(()); - }; - if field == 6 && payload.len() == 8 { - let rounds = u64::from_le_bytes(payload.try_into().expect("length checked")); - if rounds > MAX_AES_KDF_ROUNDS { - return Err(extreme_kdf_error(format_args!( - "AES-KDF round count ({rounds})" - ))); - } - return Ok(()); - } - offset = end; - } -} - -fn validate_kdbx4_kdf(bytes: &[u8]) -> Result<(), KdbxReadError> { - let mut offset = 12usize; - loop { - let field = match bytes.get(offset) { - Some(value) => *value, - None => return Ok(()), - }; - if field == 0 { - return Ok(()); - } - let Some(length) = read_le_u32(bytes, offset + 1) else { - return Ok(()); - }; - let start = offset + 5; - let end = start + length as usize; - let Some(payload) = bytes.get(start..end) else { - return Ok(()); - }; - if field == 11 { - return validate_kdbx4_kdf_parameters(payload); - } - offset = end; - } -} - -fn validate_kdbx4_kdf_parameters(payload: &[u8]) -> Result<(), KdbxReadError> { - // VariantDictionary: u16 version, then (type u8, key, value) entries. - let mut offset = 2usize; - let mut uuid: Option<[u8; 16]> = None; - let mut rounds: Option = None; - let mut memory_bytes: Option = None; - let mut iterations: Option = None; - let mut parallelism: Option = None; - while offset < payload.len() { - let value_type = payload[offset]; - offset += 1; - if value_type == 0 { - break; - } - let Some(key_length) = read_le_u32(payload, offset) else { - return Ok(()); - }; - offset += 4; - let key_end = offset + key_length as usize; - let Some(key) = payload.get(offset..key_end) else { - return Ok(()); - }; - offset = key_end; - let Some(value_length) = read_le_u32(payload, offset) else { - return Ok(()); - }; - offset += 4; - let value_end = offset + value_length as usize; - let Some(value) = payload.get(offset..value_end) else { - return Ok(()); - }; - offset = value_end; - if key == b"$UUID" && value_type == 0x0C && value.len() == 16 { - let mut parsed = [0u8; 16]; - parsed.copy_from_slice(value); - uuid = Some(parsed); - } else if key == b"R" && value_type == 0x05 { - rounds = read_le_u64(value, 0); - } else if key == b"M" && value_type == 0x05 { - memory_bytes = read_le_u64(value, 0); - } else if key == b"I" && value_type == 0x05 { - iterations = read_le_u64(value, 0); - } else if key == b"P" && value_type == 0x04 { - parallelism = read_le_u32(value, 0); - } - } - let Some(uuid) = uuid else { - return Ok(()); - }; - if uuid == UUID_AES_KDF { - if let Some(rounds) = rounds { - if rounds > MAX_AES_KDF_ROUNDS { - return Err(extreme_kdf_error(format_args!( - "AES-KDF round count ({rounds})" - ))); - } - } - return Ok(()); - } - if uuid != UUID_ARGON2D && uuid != UUID_ARGON2ID { - // Unknown KDFs are rejected by the reader itself, quickly. - return Ok(()); - } - if let Some(memory) = memory_bytes { - if memory > MAX_ARGON2_MEMORY_BYTES { - return Err(extreme_kdf_error(format_args!( - "Argon2 memory size ({memory} bytes)" - ))); - } - } - if let Some(iterations) = iterations { - if iterations > MAX_ARGON2_ITERATIONS { - return Err(extreme_kdf_error(format_args!( - "Argon2 iteration count ({iterations})" - ))); - } - } - if let Some(parallelism) = parallelism { - if parallelism > MAX_ARGON2_PARALLELISM { - return Err(extreme_kdf_error(format_args!( - "Argon2 parallelism ({parallelism})" - ))); - } - } - if let (Some(memory), Some(iterations)) = (memory_bytes, iterations) { - let work = (memory / (1024 * 1024)).saturating_mul(iterations); - if work > MAX_ARGON2_WORK_MIB_ITERATIONS { - return Err(extreme_kdf_error(format_args!( - "Argon2 work factor ({memory} bytes x {iterations} iterations)" - ))); - } - } - Ok(()) -} - -fn open_with_keepass(bytes: &[u8], password: &str) -> Result { - guard_keepass(|| { - let mut cursor = Cursor::new(bytes); - let key = DatabaseKey::new().with_password(password); - KpDatabase::open(&mut cursor, key) - }) -} - -fn xml_with_keepass(bytes: &[u8], password: &str) -> Result, KdbxReadError> { - guard_keepass(|| { - let mut cursor = Cursor::new(bytes); - let key = DatabaseKey::new().with_password(password); - KpDatabase::get_xml(&mut cursor, key) - }) -} - -/// Parse a KDBX byte buffer into the core model. -/// -/// * `password` is used only to derive the key; it never enters errors/dumps. -/// * The returned model keeps `raw_xml` (not serialized) and its SHA-256 so -/// unknown data can be preserved without leaking plaintext XML in dumps. -pub fn parse(bytes: &[u8], password: &str) -> Result { - let header = bytes - .get(..12) - .ok_or_else(|| KdbxReadError::Header("shorter than 12 bytes".to_string()))?; - let version = detect_version(header).map_err(|error| match error { - crate::kdbx::KdbxHeaderError::TooShort => { - KdbxReadError::Corrupt("header shorter than 12 bytes".to_string()) - } - crate::kdbx::KdbxHeaderError::BadSignature => { - KdbxReadError::Corrupt("not a KDBX file (bad signature)".to_string()) - } - crate::kdbx::KdbxHeaderError::UnknownVersion(version) => { - KdbxReadError::Unsupported(format!("unknown KDBX version word 0x{version:08X}")) - } - })?; - - validate_kdf_cost(bytes, version)?; - let kp = open_with_keepass(bytes, password)?; - let xml = xml_with_keepass(bytes, password)?; - let xml_hash = { - let digest = Sha256::digest(&xml); - let mut out = String::with_capacity(digest.len() * 2); - for byte in digest { - out.push_str(&format!("{byte:02x}")); - } - out - }; - - let meta = meta_from(&kp.meta, &kp); - let root = group_from(&kp.root(), &kp); - - let mut deleted_objects: Vec = kp - .deleted_objects - .iter() - .map(|(uuid, time)| DeletedObject { - uuid: uuid_from_display(uuid), - deletion_time: time.map(format_time).unwrap_or_default(), - }) - .collect(); - deleted_objects.sort_by_key(|a| a.uuid); - - Ok(Database { - format_version: version.as_str().to_string(), - meta, - root, - deleted_objects, - unknown: Vec::new(), - raw_xml: Some(xml), - raw_xml_sha256: Some(xml_hash), - }) -} - -/// Format a `chrono::NaiveDateTime` (or any displayable time) as KDBX XML text. -/// -/// The concrete type comes from the `keepass` API, so this module does not need -/// a direct `chrono` dependency. `Display` for `NaiveDateTime` is -/// `YYYY-MM-DD HH:MM:SS`; KDBX uses `T` and a trailing `Z`. -fn format_time(value: T) -> String { - let text = value.to_string(); - let text = text.replacen(' ', "T", 1); - format!("{text}Z") -} - -fn uuid_from_display(value: impl fmt::Display) -> Uuid { - value.to_string().parse().unwrap_or_default() -} - -fn icon_id(icon: Option<&Icon>) -> u32 { - match icon { - Some(Icon::BuiltIn(index)) => u32::try_from(*index).unwrap_or(0), - _ => 0, - } -} - -fn times_from(times: &KpTimes) -> Times { - Times { - creation: times.creation.map(format_time).unwrap_or_default(), - last_modification: times.last_modification.map(format_time).unwrap_or_default(), - last_access: times.last_access.map(format_time).unwrap_or_default(), - expiry: format_time(times.expiry), - expires: times.expires.unwrap_or(false), - usage_count: times.usage_count.unwrap_or(0) as u64, - location_changed: times.location_changed.map(format_time).unwrap_or_default(), - unknown: Vec::new(), - } -} - -fn custom_data_from(map: &std::collections::HashMap) -> CustomData { - let mut items = BTreeMap::new(); - for (key, item) in map { - items.insert( - key.clone(), - CustomDataItem { - value: item.value.as_ref().map(|value| match value { - KpCustomDataValue::String(text) => CustomDataValue::String(text.clone()), - KpCustomDataValue::Binary(bytes) => CustomDataValue::Binary(bytes.clone()), - }), - last_modification: item.last_modification_time.map(format_time), - unknown: Vec::new(), - }, - ); - } - CustomData { - items, - unknown: Vec::new(), - } -} - -fn memory_protection_from(protection: Option<&keepass::db::MemoryProtection>) -> MemoryProtection { - let mut out = MemoryProtection::default(); - if let Some(protection) = protection { - out.protect_title = protection.protect_title; - out.protect_username = protection.protect_username; - out.protect_password = protection.protect_password; - out.protect_url = protection.protect_url; - out.protect_notes = protection.protect_notes; - } - out -} - -fn meta_from(meta: &keepass::db::Meta, db: &KpDatabase) -> Meta { - let mut custom_icons = Vec::new(); - for icon in db.iter_all_custom_icons() { - custom_icons.push(crate::model::CustomIcon { - uuid: uuid_from_display(icon.id().uuid()), - data: icon.data.clone(), - name: icon.name.clone(), - last_modification: icon.last_modification_time.map(format_time), - unknown: Vec::new(), - }); - } - custom_icons.sort_by_key(|a| a.uuid); - Meta { - generator: meta.generator.clone().unwrap_or_default(), - database_name: meta.database_name.clone().unwrap_or_default(), - database_description: meta.database_description.clone().unwrap_or_default(), - default_username: meta.default_username.clone().unwrap_or_default(), - memory_protection: memory_protection_from(meta.memory_protection.as_ref()), - recycle_bin_enabled: meta.recyclebin_enabled.unwrap_or(false), - recycle_bin_uuid: meta.recyclebin_uuid.map(uuid_from_display), - recycle_bin_changed: meta.recyclebin_changed.map(format_time), - history_max_items: meta.history_max_items.unwrap_or(0) as i64, - history_max_size: meta.history_max_size.unwrap_or(0) as i64, - custom_data: custom_data_from(&meta.custom_data), - custom_icons, - unknown: Vec::new(), - } -} - -fn group_from(group: &keepass::db::GroupRef<'_>, db: &KpDatabase) -> Group { - let _ = db; - Group { - uuid: uuid_from_display(group.id()), - name: group.name.clone(), - notes: group.notes.clone().unwrap_or_default(), - icon_id: icon_id(group.icon()), - times: times_from(&group.times), - is_expanded: group.is_expanded, - default_auto_type: group.enable_autotype.unwrap_or(false), - default_autotype_sequence: group.default_autotype_sequence.clone().unwrap_or_default(), - enable_auto_type: group.enable_autotype.unwrap_or(false), - enable_searching: group.enable_searching.unwrap_or(false), - last_top_visible_entry: None, - tags: group.tags.clone(), - previous_parent_group: None, - custom_data: custom_data_from(&group.custom_data), - groups: group.groups().map(|child| group_from(&child, db)).collect(), - entries: group - .entries() - .map(|entry| entry_from(&entry, db)) - .collect(), - unknown: Vec::new(), - } -} - -fn entry_from(entry: &keepass::db::EntryRef<'_>, db: &KpDatabase) -> Entry { - let _ = db; - let strings = { - let mut fields = entry - .fields - .iter() - .map(|(key, value)| StringField { - key: key.clone(), - value: value.get().clone(), - protected: value.is_protected(), - unknown: Vec::new(), - }) - .collect::>(); - fields.sort_by(|a, b| a.key.cmp(&b.key)); - fields - }; - let binaries = { - let mut binaries = entry - .attachments_named() - .map(|(name, attachment)| Binary { - key: name.to_string(), - value: attachment.data.get().clone(), - protected: attachment.data.is_protected(), - unknown: Vec::new(), - }) - .collect::>(); - binaries.sort_by(|a, b| a.key.cmp(&b.key)); - binaries - }; - let mut history = Vec::new(); - let mut index = 0usize; - while let Some(previous) = entry.historical(index) { - history.push(entry_from(&previous, db)); - index += 1; - } - Entry { - uuid: uuid_from_display(entry.id()), - icon_id: icon_id(entry.icon()), - foreground_color: entry - .foreground_color - .as_ref() - .map(ToString::to_string) - .unwrap_or_default(), - background_color: entry - .background_color - .as_ref() - .map(ToString::to_string) - .unwrap_or_default(), - override_url: entry.override_url.clone().unwrap_or_default(), - tags: entry.tags.clone(), - previous_parent_group: None, - times: times_from(&entry.times), - strings, - binaries, - auto_type: entry.autotype.as_ref().map(auto_type_from), - history, - custom_data: custom_data_from(&entry.custom_data), - unknown: Vec::new(), - } -} - -fn auto_type_from(auto_type: &KpAutoType) -> AutoType { - AutoType { - enabled: auto_type.enabled, - data_transfer_obfuscation: matches!( - auto_type.data_transfer_obfuscation, - DataTransferObfuscation::UseClipboard - ), - default_sequence: auto_type.default_sequence.clone().unwrap_or_default(), - associations: auto_type - .associations - .iter() - .map(|association| Association { - window: association.window.clone(), - keystroke_sequence: association.sequence.clone(), - unknown: Vec::new(), - }) - .collect(), - unknown: Vec::new(), - } -} -#[cfg(test)] -mod kdf_limit_tests { - use super::{ - validate_kdf_cost, KdbxVersion, MAX_AES_KDF_ROUNDS, MAX_ARGON2_ITERATIONS, - MAX_ARGON2_MEMORY_BYTES, MAX_ARGON2_PARALLELISM, - }; - - const UUID_AES: [u8; 16] = [ - 0xC9, 0xD9, 0xF3, 0x9A, 0x62, 0x8A, 0x44, 0x60, 0xBF, 0x74, 0x0D, 0x08, 0xC1, 0x8A, 0x4F, - 0xEA, - ]; - const UUID_ARGON2ID: [u8; 16] = [ - 0x9E, 0x29, 0x8B, 0x19, 0x56, 0xDB, 0x47, 0x73, 0xB2, 0x3D, 0xFC, 0x3E, 0xC6, 0xF0, 0xA1, - 0xE6, - ]; - - fn variant_entry(value_type: u8, key: &[u8], value: &[u8]) -> Vec { - let mut entry = vec![value_type]; - entry.extend_from_slice(&(key.len() as u32).to_le_bytes()); - entry.extend_from_slice(key); - entry.extend_from_slice(&(value.len() as u32).to_le_bytes()); - entry.extend_from_slice(value); - entry - } - - fn u64_entry(key: &[u8], value: u64) -> Vec { - variant_entry(0x05, key, &value.to_le_bytes()) - } - - fn u32_entry(key: &[u8], value: u32) -> Vec { - variant_entry(0x04, key, &value.to_le_bytes()) - } - - fn variant_dictionary(entries: &[Vec]) -> Vec { - let mut dictionary = vec![0x00, 0x01]; - for entry in entries { - dictionary.extend_from_slice(entry); - } - dictionary.push(0); - dictionary - } - - fn kdbx3_header(rounds: u64) -> Vec { - let mut bytes = vec![ - 0x03, 0xD9, 0xA2, 0x9A, 0x67, 0xFB, 0x4B, 0xB5, 0x01, 0x00, 0x03, 0x00, - ]; - bytes.push(0x06); - bytes.extend_from_slice(&8u16.to_le_bytes()); - bytes.extend_from_slice(&rounds.to_le_bytes()); - bytes.push(0x00); - bytes.extend_from_slice(&4u16.to_le_bytes()); - bytes.extend_from_slice(&[0x0D, 0x0A, 0x0D, 0x0A]); - bytes - } - - fn kdbx4_header(dictionary: Vec) -> Vec { - let mut bytes = vec![ - 0x03, 0xD9, 0xA2, 0x9A, 0x67, 0xFB, 0x4B, 0xB5, 0x00, 0x00, 0x04, 0x00, - ]; - bytes.push(0x0B); - bytes.extend_from_slice(&(dictionary.len() as u32).to_le_bytes()); - bytes.extend_from_slice(&dictionary); - bytes.push(0x00); - bytes.extend_from_slice(&4u32.to_le_bytes()); - bytes.extend_from_slice(&[0x0D, 0x0A, 0x0D, 0x0A]); - bytes - } - - fn argon2_dictionary( - uuid: [u8; 16], - memory: u64, - iterations: u64, - parallelism: u32, - ) -> Vec { - variant_dictionary(&[ - variant_entry(0x0C, b"$UUID", &uuid), - u64_entry(b"M", memory), - u64_entry(b"I", iterations), - u32_entry(b"P", parallelism), - ]) - } - - #[test] - fn normal_kdbx31_rounds_pass() { - assert!(validate_kdf_cost(&kdbx3_header(600_000), KdbxVersion::V3_1).is_ok()); - assert!(validate_kdf_cost(&kdbx3_header(MAX_AES_KDF_ROUNDS), KdbxVersion::V3_1).is_ok()); - } - - #[test] - fn extreme_kdbx31_rounds_are_rejected() { - let error = validate_kdf_cost(&kdbx3_header(MAX_AES_KDF_ROUNDS + 1), KdbxVersion::V3_1) - .expect_err("an extreme round count must be rejected"); - assert!(matches!(error, super::KdbxReadError::Unsupported(_))); - } - - #[test] - fn normal_argon2id_parameters_pass() { - let bytes = kdbx4_header(argon2_dictionary(UUID_ARGON2ID, 128 * 1024 * 1024, 6, 4)); - assert!(validate_kdf_cost(&bytes, KdbxVersion::V4_0).is_ok()); - } - - #[test] - fn extreme_argon2_parameters_are_rejected() { - for (memory, iterations, parallelism) in [ - (MAX_ARGON2_MEMORY_BYTES + 1, 1, 1), - (128 * 1024 * 1024, MAX_ARGON2_ITERATIONS + 1, 1), - (128 * 1024 * 1024, 1, MAX_ARGON2_PARALLELISM + 1), - (2 * 1024 * 1024 * 1024, 8, 4), // within per-field caps, over the work cap - ] { - let bytes = kdbx4_header(argon2_dictionary( - UUID_ARGON2ID, - memory, - iterations, - parallelism, - )); - assert!( - validate_kdf_cost(&bytes, KdbxVersion::V4_0).is_err(), - "memory={memory} iterations={iterations} parallelism={parallelism} must be rejected" - ); - } - } - - #[test] - fn normal_aes_kdf_in_kdbx4_passes() { - let dictionary = variant_dictionary(&[ - variant_entry(0x0C, b"$UUID", &UUID_AES), - u64_entry(b"R", 600_000), - ]); - assert!(validate_kdf_cost(&kdbx4_header(dictionary), KdbxVersion::V4_0).is_ok()); - } - - #[test] - fn unknown_kdf_is_left_to_the_reader() { - let dictionary = variant_dictionary(&[variant_entry(0x0C, b"$UUID", &[0x42; 16])]); - assert!(validate_kdf_cost(&kdbx4_header(dictionary), KdbxVersion::V4_0).is_ok()); - } -} diff --git a/crates/core/src/kdbx/reader/convert.rs b/crates/core/src/kdbx/reader/convert.rs new file mode 100644 index 0000000..ed9a465 --- /dev/null +++ b/crates/core/src/kdbx/reader/convert.rs @@ -0,0 +1,241 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Converting the parser's groups, entries and metadata into the core model. + +use super::*; + +/// Rejects headers whose KDF parameters would make key derivation take far too +/// long. Called before the third-party reader runs; a file that fails here is a +/// normal read error (never a panic and never a multi-minute stall). +pub(crate) fn validate_kdf_cost(bytes: &[u8], version: KdbxVersion) -> Result<(), KdbxReadError> { + match version { + KdbxVersion::V3_1 => validate_kdbx3_kdf(bytes), + KdbxVersion::V4_0 | KdbxVersion::V4_1 => validate_kdbx4_kdf(bytes), + } +} + +/// Format a `chrono::NaiveDateTime` (or any displayable time) as KDBX XML text. +/// +/// The concrete type comes from the `keepass` API, so this module does not need +/// a direct `chrono` dependency. `Display` for `NaiveDateTime` is +/// `YYYY-MM-DD HH:MM:SS`; KDBX uses `T` and a trailing `Z`. +pub(crate) fn format_time(value: T) -> String { + let text = value.to_string(); + let text = text.replacen(' ', "T", 1); + format!("{text}Z") +} + +pub(crate) fn uuid_from_display(value: impl fmt::Display) -> Uuid { + value.to_string().parse().unwrap_or_default() +} + +pub(crate) fn icon_id(icon: Option<&Icon>) -> u32 { + match icon { + Some(Icon::BuiltIn(index)) => u32::try_from(*index).unwrap_or(0), + _ => 0, + } +} + +pub(crate) fn custom_icon_uuid(icon: Option<&Icon>) -> Option { + match icon { + Some(Icon::Custom(id)) => Some(uuid_from_display(id.uuid())), + _ => None, + } +} + +pub(crate) fn times_from(times: &KpTimes) -> Times { + Times { + creation: times.creation.map(format_time).unwrap_or_default(), + last_modification: times.last_modification.map(format_time).unwrap_or_default(), + last_access: times.last_access.map(format_time).unwrap_or_default(), + expiry: format_time(times.expiry), + expires: times.expires.unwrap_or(false), + usage_count: times.usage_count.unwrap_or(0) as u64, + location_changed: times.location_changed.map(format_time).unwrap_or_default(), + unknown: Vec::new(), + } +} + +pub(crate) fn custom_data_from( + map: &std::collections::HashMap, +) -> CustomData { + let mut items = BTreeMap::new(); + for (key, item) in map { + items.insert( + key.clone(), + CustomDataItem { + value: item.value.as_ref().map(|value| match value { + KpCustomDataValue::String(text) => CustomDataValue::String(text.clone()), + KpCustomDataValue::Binary(bytes) => CustomDataValue::Binary(bytes.clone()), + }), + last_modification: item.last_modification_time.map(format_time), + unknown: Vec::new(), + }, + ); + } + CustomData { + items, + unknown: Vec::new(), + } +} + +pub(crate) fn memory_protection_from( + protection: Option<&keepass::db::MemoryProtection>, +) -> MemoryProtection { + let mut out = MemoryProtection::default(); + if let Some(protection) = protection { + out.protect_title = protection.protect_title; + out.protect_username = protection.protect_username; + out.protect_password = protection.protect_password; + out.protect_url = protection.protect_url; + out.protect_notes = protection.protect_notes; + } + out +} + +pub(crate) fn meta_from(meta: &keepass::db::Meta, db: &KpDatabase) -> Meta { + let mut custom_icons = Vec::new(); + for icon in db.iter_all_custom_icons() { + custom_icons.push(crate::model::CustomIcon { + uuid: uuid_from_display(icon.id().uuid()), + data: icon.data.clone(), + name: icon.name.clone(), + last_modification: icon.last_modification_time.map(format_time), + unknown: Vec::new(), + }); + } + custom_icons.sort_by_key(|a| a.uuid); + Meta { + generator: meta.generator.clone().unwrap_or_default(), + database_name: meta.database_name.clone().unwrap_or_default(), + database_description: meta.database_description.clone().unwrap_or_default(), + default_username: meta.default_username.clone().unwrap_or_default(), + memory_protection: memory_protection_from(meta.memory_protection.as_ref()), + // Omitted `` elements use the KeePass defaults, not zero: a file + // without these elements still has the recycle bin on and bounded + // history (10 items / 6 MiB). Reading them as 0 silently disabled both. + recycle_bin_enabled: meta.recyclebin_enabled.unwrap_or(true), + recycle_bin_uuid: meta.recyclebin_uuid.map(uuid_from_display), + recycle_bin_changed: meta.recyclebin_changed.map(format_time), + history_max_items: meta + .history_max_items + .map(|value| value as i64) + .unwrap_or(crate::model::DEFAULT_HISTORY_MAX_ITEMS), + history_max_size: meta + .history_max_size + .map(|value| value as i64) + .unwrap_or(crate::model::DEFAULT_HISTORY_MAX_SIZE), + custom_data: custom_data_from(&meta.custom_data), + custom_icons, + unknown: Vec::new(), + } +} + +pub(crate) fn group_from(group: &keepass::db::GroupRef<'_>, db: &KpDatabase) -> Group { + let _ = db; + Group { + uuid: uuid_from_display(group.id()), + name: group.name.clone(), + notes: group.notes.clone().unwrap_or_default(), + icon_id: icon_id(group.icon()), + custom_icon_uuid: custom_icon_uuid(group.icon()), + times: times_from(&group.times), + is_expanded: group.is_expanded, + default_auto_type: group.enable_autotype.unwrap_or(false), + default_autotype_sequence: group.default_autotype_sequence.clone().unwrap_or_default(), + enable_auto_type: group.enable_autotype.unwrap_or(false), + enable_searching: group.enable_searching.unwrap_or(false), + last_top_visible_entry: None, + tags: group.tags.clone(), + previous_parent_group: None, + custom_data: custom_data_from(&group.custom_data), + groups: group.groups().map(|child| group_from(&child, db)).collect(), + entries: group + .entries() + .map(|entry| entry_from(&entry, db)) + .collect(), + unknown: Vec::new(), + } +} + +pub(crate) fn entry_from(entry: &keepass::db::EntryRef<'_>, db: &KpDatabase) -> Entry { + let _ = db; + let strings = { + let mut fields = entry + .fields + .iter() + .map(|(key, value)| StringField { + key: key.clone(), + value: value.get().clone(), + protected: value.is_protected(), + unknown: Vec::new(), + }) + .collect::>(); + fields.sort_by(|a, b| a.key.cmp(&b.key)); + fields + }; + let binaries = { + let mut binaries = entry + .attachments_named() + .map(|(name, attachment)| Binary { + key: name.to_string(), + value: attachment.data.get().clone(), + protected: attachment.data.is_protected(), + unknown: Vec::new(), + }) + .collect::>(); + binaries.sort_by(|a, b| a.key.cmp(&b.key)); + binaries + }; + let mut history = Vec::new(); + let mut index = 0usize; + while let Some(previous) = entry.historical(index) { + history.push(entry_from(&previous, db)); + index += 1; + } + Entry { + uuid: uuid_from_display(entry.id()), + icon_id: icon_id(entry.icon()), + custom_icon_uuid: custom_icon_uuid(entry.icon()), + foreground_color: entry + .foreground_color + .as_ref() + .map(ToString::to_string) + .unwrap_or_default(), + background_color: entry + .background_color + .as_ref() + .map(ToString::to_string) + .unwrap_or_default(), + override_url: entry.override_url.clone().unwrap_or_default(), + tags: entry.tags.clone(), + previous_parent_group: None, + times: times_from(&entry.times), + strings, + binaries, + auto_type: entry.autotype.as_ref().map(auto_type_from), + history, + custom_data: custom_data_from(&entry.custom_data), + unknown: Vec::new(), + } +} + +pub(crate) fn auto_type_from(auto_type: &KpAutoType) -> AutoType { + AutoType { + enabled: auto_type.enabled, + data_transfer_obfuscation: matches!( + auto_type.data_transfer_obfuscation, + DataTransferObfuscation::UseClipboard + ), + default_sequence: auto_type.default_sequence.clone().unwrap_or_default(), + associations: auto_type + .associations + .iter() + .map(|association| Association { + window: association.window.clone(), + keystroke_sequence: association.sequence.clone(), + unknown: Vec::new(), + }) + .collect(), + unknown: Vec::new(), + } +} diff --git a/crates/core/src/kdbx/reader/error.rs b/crates/core/src/kdbx/reader/error.rs new file mode 100644 index 0000000..c28b74b --- /dev/null +++ b/crates/core/src/kdbx/reader/error.rs @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! The read error type and the panic guard around the keepass parser. + +use super::*; + +/// Error returned by the KDBX reader. +#[derive(Debug)] +pub enum KdbxReadError { + /// Wrong password/key (or a key-like failure). + BadPassword, + /// Corrupt/truncated data, bad HMAC, or unparsable content. + Corrupt(String), + /// Unsupported KDBX version or format feature. + Unsupported(String), + /// Header is missing/unknown. + Header(String), +} + +impl fmt::Display for KdbxReadError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::BadPassword => write!(f, "bad password or key (database could not be decrypted)"), + Self::Corrupt(message) => write!(f, "corrupt KDBX database: {message}"), + Self::Unsupported(message) => write!(f, "unsupported KDBX database: {message}"), + Self::Header(message) => write!(f, "invalid KDBX header: {message}"), + } + } +} + +impl std::error::Error for KdbxReadError {} + +pub(crate) fn classify_open_error(error: &impl fmt::Debug) -> KdbxReadError { + let raw = format!("{error:?}"); + if raw.contains("IncorrectKey") || raw.contains("EmptyKey") { + KdbxReadError::BadPassword + } else if raw.contains("UnsupportedVersion") || raw.contains("VersionParse") { + KdbxReadError::Unsupported(raw) + } else if raw.contains("UnexpectedEof") { + KdbxReadError::Corrupt("unexpected end of file".to_string()) + } else { + KdbxReadError::Corrupt(raw) + } +} + +/// Run one upstream `keepass` reader call and turn a panic into a parse error. +/// +/// The upstream `keepass` crate (0.17) panics instead of returning an error for +/// a few malformed header shapes (for example a variant dictionary whose length +/// field points past the end of the buffer: `byteorder::read_u64` indexes out of +/// bounds). A KDBX file is untrusted input - it arrives from WebDAV, a shared +/// folder or the file manager - so a malformed file must surface as a normal +/// read error, not abort the application or the fuzzer. The panic message +/// carries no secret material; it is dropped here and the reason is reported as +/// "malformed header" instead. +pub(crate) fn guard_keepass( + call: impl FnOnce() -> Result, +) -> Result { + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(call)) { + Ok(Ok(value)) => Ok(value), + Ok(Err(error)) => Err(classify_open_error(&error)), + Err(_) => Err(KdbxReadError::Corrupt( + "malformed KDBX header (the upstream reader panicked; file rejected)".to_string(), + )), + } +} diff --git a/crates/core/src/kdbx/reader/header.rs b/crates/core/src/kdbx/reader/header.rs new file mode 100644 index 0000000..ce40598 --- /dev/null +++ b/crates/core/src/kdbx/reader/header.rs @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Parsing the outer header and its KDF settings. + +use super::*; + +/// Read the KDBX4 outer header fields that the writer must preserve. Returns +/// `None` for KDBX 3.1 (the writer intentionally upgrades it to KDBX 4) or a +/// header whose cipher/compression is unknown to the write backend. +pub(crate) fn parse_outer_header(bytes: &[u8], version: KdbxVersion) -> Option { + if !matches!(version, KdbxVersion::V4_0 | KdbxVersion::V4_1) { + return None; + } + let mut offset = 12usize; + let mut cipher: Option = None; + let mut compression: Option = None; + let mut kdf: Option = None; + let mut public_custom_data: Option> = None; + while let Some(value) = bytes.get(offset) { + let field = *value; + if field == 0 { + break; + } + let length = read_le_u32(bytes, offset + 1)? as usize; + let start = offset + 5; + let end = start.checked_add(length)?; + let payload = bytes.get(start..end)?; + match field { + 2 if payload.len() == 16 => { + let mut uuid = [0u8; 16]; + uuid.copy_from_slice(payload); + cipher = match uuid { + CIPHER_AES128 => Some(OuterCipher::Aes128), + CIPHER_AES256 => Some(OuterCipher::Aes256), + CIPHER_TWOFISH => Some(OuterCipher::Twofish), + CIPHER_CHACHA20 => Some(OuterCipher::ChaCha20), + _ => return None, + }; + } + 3 if payload.len() == 4 => { + compression = match read_le_u32(payload, 0)? { + 0 => Some(OuterCompression::None), + 1 => Some(OuterCompression::Gzip), + _ => return None, + }; + } + 11 => kdf = parse_kdf_settings(payload), + 12 => public_custom_data = Some(payload.to_vec()), + _ => {} + } + offset = end; + } + Some(OuterHeader { + version: version.as_str().to_string(), + cipher: cipher?, + compression: compression?, + kdf, + public_custom_data, + }) +} + +/// Parse a KDBX4 VariantDictionary KDF block into the model settings. +pub(crate) fn parse_kdf_settings(payload: &[u8]) -> Option { + let mut offset = 2usize; + let mut uuid: Option<[u8; 16]> = None; + let mut rounds: Option = None; + let mut memory_bytes: Option = None; + let mut iterations: Option = None; + let mut parallelism: Option = None; + let mut argon_version: Option = None; + while offset < payload.len() { + let value_type = *payload.get(offset)?; + offset += 1; + if value_type == 0 { + break; + } + let key_length = read_le_u32(payload, offset)? as usize; + offset += 4; + let key_end = offset.checked_add(key_length)?; + let key = payload.get(offset..key_end)?; + offset = key_end; + let value_length = read_le_u32(payload, offset)? as usize; + offset += 4; + let value_end = offset.checked_add(value_length)?; + let value = payload.get(offset..value_end)?; + offset = value_end; + match key { + b"$UUID" + if matches!(value_type, VARIANT_BYTE_ARRAY | VARIANT_INT32) + && value.len() == 16 => + { + let mut parsed = [0u8; 16]; + parsed.copy_from_slice(value); + uuid = Some(parsed); + } + b"R" if value_type == 0x05 => rounds = read_le_u64(value, 0), + b"M" if value_type == 0x05 => memory_bytes = read_le_u64(value, 0), + b"I" if value_type == 0x05 => iterations = read_le_u64(value, 0), + b"P" if value_type == 0x04 => parallelism = read_le_u32(value, 0), + b"V" if value_type == 0x04 => argon_version = read_le_u32(value, 0), + _ => {} + } + } + let uuid = uuid?; + match uuid { + UUID_AES_KDF => Some(KdfSettings::Aes { rounds: rounds? }), + UUID_ARGON2D | UUID_ARGON2ID => { + let memory_bytes = memory_bytes?; + if memory_bytes % 1024 != 0 { + // The backend represents Argon2 memory in KiB; do not round a + // user's KDF silently. + return None; + } + let memory_kib = u32::try_from(memory_bytes / 1024).ok()?; + let iterations = u32::try_from(iterations?).ok()?; + Some(KdfSettings::Argon2 { + kind: if uuid == UUID_ARGON2ID { + Argon2Kind::Id + } else { + Argon2Kind::D + }, + iterations, + memory_kib, + parallelism: parallelism?, + version: argon_version.unwrap_or(0x13), + }) + } + _ => None, + } +} diff --git a/crates/core/src/kdbx/reader/limits.rs b/crates/core/src/kdbx/reader/limits.rs new file mode 100644 index 0000000..92dce0b --- /dev/null +++ b/crates/core/src/kdbx/reader/limits.rs @@ -0,0 +1,248 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! KDF and header limits, the little-endian readers and the validation that +//! refuses a database whose KDF parameters would hang or exhaust the machine. + +use super::*; + +/// Upper bounds for the key-derivation work a KDBX file may ask for. +/// +/// The header is untrusted input: it can name arbitrary KDF parameters, and the +/// reader would otherwise spend unbounded time (or memory) deriving a key from a +/// hostile file before even noticing a wrong password. The daily fuzzing job +/// found exactly that shape (a KDBX 3.1 header with ~2e18 AES-KDF rounds made the +/// reader run for minutes). The limits are far above real-world databases - the +/// writer's default is 128 MiB / 6 iterations / 4 lanes, about 0.7 s - and only +/// reject requests that are clearly meant to exhaust the machine. +pub(crate) const MAX_AES_KDF_ROUNDS: u64 = 10_000_000; +pub(crate) const MAX_ARGON2_MEMORY_BYTES: u64 = 2 * 1024 * 1024 * 1024; +pub(crate) const MAX_ARGON2_ITERATIONS: u64 = 64; +pub(crate) const MAX_ARGON2_PARALLELISM: u32 = 16; +/// `memory (MiB) * iterations` bound; about eight times the write default. +pub(crate) const MAX_ARGON2_WORK_MIB_ITERATIONS: u64 = 6_144; + +pub(crate) const UUID_AES_KDF: [u8; 16] = [ + 0xC9, 0xD9, 0xF3, 0x9A, 0x62, 0x8A, 0x44, 0x60, 0xBF, 0x74, 0x0D, 0x08, 0xC1, 0x8A, 0x4F, 0xEA, +]; +pub(crate) const UUID_ARGON2D: [u8; 16] = [ + 0xEF, 0x63, 0x6D, 0xDF, 0x8C, 0x29, 0x44, 0x4B, 0x91, 0xF7, 0xA9, 0xA4, 0x03, 0xE3, 0x0A, 0x0C, +]; +pub(crate) const UUID_ARGON2ID: [u8; 16] = [ + 0x9E, 0x29, 0x8B, 0x19, 0x56, 0xDB, 0x47, 0x73, 0xB2, 0x3D, 0xFC, 0x3E, 0xC6, 0xF0, 0xA1, 0xE6, +]; + +pub(crate) const CIPHER_AES128: [u8; 16] = [ + 0x61, 0xAB, 0x05, 0xA1, 0x94, 0x64, 0x41, 0xC3, 0x8D, 0x74, 0x3A, 0x56, 0x3D, 0xF8, 0xDD, 0x35, +]; +pub(crate) const CIPHER_AES256: [u8; 16] = [ + 0x31, 0xC1, 0xF2, 0xE6, 0xBF, 0x71, 0x43, 0x50, 0xBE, 0x58, 0x05, 0x21, 0x6A, 0xFC, 0x5A, 0xFF, +]; +pub(crate) const CIPHER_TWOFISH: [u8; 16] = [ + 0xAD, 0x68, 0xF2, 0x9F, 0x57, 0x6F, 0x4B, 0xB9, 0xA3, 0x6A, 0xD4, 0x7A, 0xF9, 0x65, 0x34, 0x6C, +]; +pub(crate) const CIPHER_CHACHA20: [u8; 16] = [ + 0xD6, 0x03, 0x8A, 0x2B, 0x8B, 0x6F, 0x4C, 0xB5, 0xA5, 0x24, 0x33, 0x9A, 0x31, 0xDB, 0xB5, 0x9A, +]; + +/// VariantDictionary value type for a byte array (the KDBX 4 specification's +/// type for `$UUID`). Real files use this, not the Int32 type. +pub(crate) const VARIANT_BYTE_ARRAY: u8 = 0x42; +/// VariantDictionary Int32 value type. Early versions of this validator +/// accepted it for `$UUID`; keep reading it for compatibility. +pub(crate) const VARIANT_INT32: u8 = 0x0C; + +pub(crate) fn extreme_kdf_error(detail: impl fmt::Display) -> KdbxReadError { + KdbxReadError::Unsupported(format!( + "the database asks for an extreme {detail} (opening it would take a very long \ + time); open it in KeePass and re-save it with normal KDF settings" + )) +} + +pub(crate) fn read_le_u16(bytes: &[u8], offset: usize) -> Option { + Some(u16::from_le_bytes( + bytes.get(offset..offset + 2)?.try_into().ok()?, + )) +} + +pub(crate) fn read_le_u32(bytes: &[u8], offset: usize) -> Option { + Some(u32::from_le_bytes( + bytes.get(offset..offset + 4)?.try_into().ok()?, + )) +} + +pub(crate) fn read_le_u64(bytes: &[u8], offset: usize) -> Option { + Some(u64::from_le_bytes( + bytes.get(offset..offset + 8)?.try_into().ok()?, + )) +} + +pub(crate) fn validate_kdbx3_kdf(bytes: &[u8]) -> Result<(), KdbxReadError> { + let mut offset = 12usize; + let mut rounds: Option = None; + let mut saw_rounds = false; + while let Some(value) = bytes.get(offset) { + let field = *value; + if field == 0 { + break; + } + let Some(length) = read_le_u16(bytes, offset + 1) else { + break; + }; + let start = offset + 3; + let end = start + length as usize; + let Some(payload) = bytes.get(start..end) else { + break; + }; + if field == 6 { + // The header parser uses the last occurrence; a duplicate field + // would let a hostile file hide one value from this validator. + if saw_rounds { + return Err(KdbxReadError::Header( + "duplicate KDBX 3 transform-rounds header field".to_string(), + )); + } + saw_rounds = true; + rounds = read_le_u64(payload, 0); + } + offset = end; + } + if let Some(rounds) = rounds { + if rounds > MAX_AES_KDF_ROUNDS { + return Err(extreme_kdf_error(format_args!( + "AES-KDF round count ({rounds})" + ))); + } + } + Ok(()) +} + +pub(crate) fn validate_kdbx4_kdf(bytes: &[u8]) -> Result<(), KdbxReadError> { + let mut offset = 12usize; + let mut parameters: Option<&[u8]> = None; + while let Some(value) = bytes.get(offset) { + let field = *value; + if field == 0 { + break; + } + let Some(length) = read_le_u32(bytes, offset + 1) else { + break; + }; + let start = offset + 5; + let end = start + length as usize; + let Some(payload) = bytes.get(start..end) else { + break; + }; + if field == 11 { + // keepass 0.17 keeps the last KDBX4 KDF-parameters field. Reject + // duplicates instead of validating one field and using another. + if parameters.is_some() { + return Err(KdbxReadError::Header( + "duplicate KDBX 4 KDF parameters header field".to_string(), + )); + } + parameters = Some(payload); + } + offset = end; + } + match parameters { + Some(payload) => validate_kdbx4_kdf_parameters(payload), + None => Ok(()), + } +} + +pub(crate) fn validate_kdbx4_kdf_parameters(payload: &[u8]) -> Result<(), KdbxReadError> { + // VariantDictionary: u16 version, then (type u8, key, value) entries. + let mut offset = 2usize; + let mut uuid: Option<[u8; 16]> = None; + let mut rounds: Option = None; + let mut memory_bytes: Option = None; + let mut iterations: Option = None; + let mut parallelism: Option = None; + while offset < payload.len() { + let value_type = payload[offset]; + offset += 1; + if value_type == 0 { + break; + } + let Some(key_length) = read_le_u32(payload, offset) else { + return Ok(()); + }; + offset += 4; + let key_end = offset + key_length as usize; + let Some(key) = payload.get(offset..key_end) else { + return Ok(()); + }; + offset = key_end; + let Some(value_length) = read_le_u32(payload, offset) else { + return Ok(()); + }; + offset += 4; + let value_end = offset + value_length as usize; + let Some(value) = payload.get(offset..value_end) else { + return Ok(()); + }; + offset = value_end; + if key == b"$UUID" + && matches!(value_type, VARIANT_BYTE_ARRAY | VARIANT_INT32) + && value.len() == 16 + { + let mut parsed = [0u8; 16]; + parsed.copy_from_slice(value); + uuid = Some(parsed); + } else if key == b"R" && value_type == 0x05 { + rounds = read_le_u64(value, 0); + } else if key == b"M" && value_type == 0x05 { + memory_bytes = read_le_u64(value, 0); + } else if key == b"I" && value_type == 0x05 { + iterations = read_le_u64(value, 0); + } else if key == b"P" && value_type == 0x04 { + parallelism = read_le_u32(value, 0); + } + } + let Some(uuid) = uuid else { + return Ok(()); + }; + if uuid == UUID_AES_KDF { + if let Some(rounds) = rounds { + if rounds > MAX_AES_KDF_ROUNDS { + return Err(extreme_kdf_error(format_args!( + "AES-KDF round count ({rounds})" + ))); + } + } + return Ok(()); + } + if uuid != UUID_ARGON2D && uuid != UUID_ARGON2ID { + // Unknown KDFs are rejected by the reader itself, quickly. + return Ok(()); + } + if let Some(memory) = memory_bytes { + if memory > MAX_ARGON2_MEMORY_BYTES { + return Err(extreme_kdf_error(format_args!( + "Argon2 memory size ({memory} bytes)" + ))); + } + } + if let Some(iterations) = iterations { + if iterations > MAX_ARGON2_ITERATIONS { + return Err(extreme_kdf_error(format_args!( + "Argon2 iteration count ({iterations})" + ))); + } + } + if let Some(parallelism) = parallelism { + if parallelism > MAX_ARGON2_PARALLELISM { + return Err(extreme_kdf_error(format_args!( + "Argon2 parallelism ({parallelism})" + ))); + } + } + if let (Some(memory), Some(iterations)) = (memory_bytes, iterations) { + let work = (memory / (1024 * 1024)).saturating_mul(iterations); + if work > MAX_ARGON2_WORK_MIB_ITERATIONS { + return Err(extreme_kdf_error(format_args!( + "Argon2 work factor ({memory} bytes x {iterations} iterations)" + ))); + } + } + Ok(()) +} diff --git a/crates/core/src/kdbx/reader/mod.rs b/crates/core/src/kdbx/reader/mod.rs new file mode 100644 index 0000000..24a8d08 --- /dev/null +++ b/crates/core/src/kdbx/reader/mod.rs @@ -0,0 +1,360 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! KDBX reader: decrypt a KDBX 3.1/4.0/4.1 byte buffer and map it onto the +//! core model. +//! +//! The established `keepass` crate (MIT) performs decryption and KDF work; this +//! module adds the mapping to our model. It performs **no file IO** — callers +//! pass the file bytes. The raw decrypted XML is retained (not serialized) so +//! that unmapped/unknown data is not lost; canonical dumps only expose its +//! SHA-256. + +use crate::kdbx::{detect_version, KdbxVersion}; +use crate::model::{Argon2Kind, KdfSettings, OuterCipher, OuterCompression, OuterHeader}; +use crate::model::{Association, AutoType, Binary, CustomData, CustomDataItem, CustomDataValue}; +use crate::model::{Database, DeletedObject, Entry, Group, MemoryProtection, Meta, StringField}; +use crate::model::{Times, Uuid}; +use keepass::db::{ + AutoType as KpAutoType, CustomDataItem as KpCustomDataItem, + CustomDataValue as KpCustomDataValue, DataTransferObfuscation, Icon, Times as KpTimes, +}; +use keepass::{Database as KpDatabase, DatabaseKey}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::fmt; +use std::io::Cursor; +#[cfg(test)] +mod kdf_limit_tests { + use super::{ + validate_kdbx4_kdf_parameters, validate_kdf_cost, KdbxReadError, KdbxVersion, + MAX_AES_KDF_ROUNDS, MAX_ARGON2_ITERATIONS, MAX_ARGON2_MEMORY_BYTES, MAX_ARGON2_PARALLELISM, + VARIANT_BYTE_ARRAY, VARIANT_INT32, + }; + + const UUID_AES: [u8; 16] = [ + 0xC9, 0xD9, 0xF3, 0x9A, 0x62, 0x8A, 0x44, 0x60, 0xBF, 0x74, 0x0D, 0x08, 0xC1, 0x8A, 0x4F, + 0xEA, + ]; + const UUID_ARGON2ID: [u8; 16] = [ + 0x9E, 0x29, 0x8B, 0x19, 0x56, 0xDB, 0x47, 0x73, 0xB2, 0x3D, 0xFC, 0x3E, 0xC6, 0xF0, 0xA1, + 0xE6, + ]; + + fn variant_entry(value_type: u8, key: &[u8], value: &[u8]) -> Vec { + let mut entry = vec![value_type]; + entry.extend_from_slice(&(key.len() as u32).to_le_bytes()); + entry.extend_from_slice(key); + entry.extend_from_slice(&(value.len() as u32).to_le_bytes()); + entry.extend_from_slice(value); + entry + } + + fn u64_entry(key: &[u8], value: u64) -> Vec { + variant_entry(0x05, key, &value.to_le_bytes()) + } + + fn u32_entry(key: &[u8], value: u32) -> Vec { + variant_entry(0x04, key, &value.to_le_bytes()) + } + + fn variant_dictionary(entries: &[Vec]) -> Vec { + let mut dictionary = vec![0x00, 0x01]; + for entry in entries { + dictionary.extend_from_slice(entry); + } + dictionary.push(0); + dictionary + } + + fn kdbx3_header(rounds: u64) -> Vec { + kdbx3_header_with_rounds(&[rounds]) + } + + fn kdbx3_header_with_rounds(rounds: &[u64]) -> Vec { + let mut bytes = vec![ + 0x03, 0xD9, 0xA2, 0x9A, 0x67, 0xFB, 0x4B, 0xB5, 0x01, 0x00, 0x03, 0x00, + ]; + for rounds in rounds { + bytes.push(0x06); + bytes.extend_from_slice(&8u16.to_le_bytes()); + bytes.extend_from_slice(&rounds.to_le_bytes()); + } + bytes.push(0x00); + bytes.extend_from_slice(&4u16.to_le_bytes()); + bytes.extend_from_slice(&[0x0D, 0x0A, 0x0D, 0x0A]); + bytes + } + + fn kdbx4_header(dictionary: Vec) -> Vec { + kdbx4_header_with_dictionaries(std::slice::from_ref(&dictionary)) + } + + fn kdbx4_header_with_dictionaries(dictionaries: &[Vec]) -> Vec { + let mut bytes = vec![ + 0x03, 0xD9, 0xA2, 0x9A, 0x67, 0xFB, 0x4B, 0xB5, 0x00, 0x00, 0x04, 0x00, + ]; + for dictionary in dictionaries { + bytes.push(0x0B); + bytes.extend_from_slice(&(dictionary.len() as u32).to_le_bytes()); + bytes.extend_from_slice(dictionary); + } + bytes.push(0x00); + bytes.extend_from_slice(&4u32.to_le_bytes()); + bytes.extend_from_slice(&[0x0D, 0x0A, 0x0D, 0x0A]); + bytes + } + + fn aes_dictionary(uuid_type: u8, rounds: u64) -> Vec { + variant_dictionary(&[ + variant_entry(uuid_type, b"$UUID", &UUID_AES), + u64_entry(b"R", rounds), + ]) + } + + fn argon2_dictionary( + uuid_type: u8, + uuid: [u8; 16], + memory: u64, + iterations: u64, + parallelism: u32, + ) -> Vec { + variant_dictionary(&[ + variant_entry(uuid_type, b"$UUID", &uuid), + u64_entry(b"M", memory), + u64_entry(b"I", iterations), + u32_entry(b"P", parallelism), + ]) + } + + fn fixture(name: &str) -> Vec { + std::fs::read(format!( + "{}/../../tests/fixtures/keepass-rs/{name}", + env!("CARGO_MANIFEST_DIR") + )) + .expect("fixture") + } + + /// Return the payload of KDBX 4 header field 11 from raw file bytes. + fn kdbx4_kdf_dictionary(bytes: &[u8]) -> &[u8] { + let mut offset = 12usize; + while offset < bytes.len() { + let field = bytes[offset]; + if field == 0 { + break; + } + let length = u32::from_le_bytes( + bytes[offset + 1..offset + 5] + .try_into() + .expect("length checked"), + ) as usize; + let start = offset + 5; + let end = start + length; + if field == 11 { + return &bytes[start..end]; + } + offset = end; + } + panic!("fixture has no KDF parameters field"); + } + + /// Overwrite the little-endian `u64` value of a key inside a dictionary. + fn set_dictionary_u64(dictionary: &mut [u8], key: &[u8], value: u64) { + let mut offset = 2usize; + while offset < dictionary.len() { + offset += 1; // value type + let key_length = u32::from_le_bytes( + dictionary[offset..offset + 4] + .try_into() + .expect("length checked"), + ) as usize; + offset += 4; + let key_end = offset + key_length; + let this_key = &dictionary[offset..key_end]; + offset = key_end; + let value_length = u32::from_le_bytes( + dictionary[offset..offset + 4] + .try_into() + .expect("length checked"), + ) as usize; + offset += 4; + if this_key == key && value_length == 8 { + dictionary[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); + return; + } + offset += value_length; + } + panic!("key not found in dictionary"); + } + + #[test] + fn normal_kdbx31_rounds_pass() { + assert!(validate_kdf_cost(&kdbx3_header(600_000), KdbxVersion::V3_1).is_ok()); + assert!(validate_kdf_cost(&kdbx3_header(MAX_AES_KDF_ROUNDS), KdbxVersion::V3_1).is_ok()); + } + + #[test] + fn extreme_kdbx31_rounds_are_rejected() { + let error = validate_kdf_cost(&kdbx3_header(MAX_AES_KDF_ROUNDS + 1), KdbxVersion::V3_1) + .expect_err("an extreme round count must be rejected"); + assert!(matches!(error, KdbxReadError::Unsupported(_))); + } + + #[test] + fn duplicate_kdbx3_round_fields_are_rejected() { + let bytes = kdbx3_header_with_rounds(&[600_000, MAX_AES_KDF_ROUNDS + 1]); + let error = validate_kdf_cost(&bytes, KdbxVersion::V3_1) + .expect_err("duplicate KDF fields must not be validated selectively"); + assert!(matches!(error, KdbxReadError::Header(_))); + } + + #[test] + fn normal_argon2id_parameters_pass() { + let bytes = kdbx4_header(argon2_dictionary( + VARIANT_BYTE_ARRAY, + UUID_ARGON2ID, + 128 * 1024 * 1024, + 6, + 4, + )); + assert!(validate_kdf_cost(&bytes, KdbxVersion::V4_0).is_ok()); + } + + #[test] + fn extreme_argon2_parameters_are_rejected() { + for (memory, iterations, parallelism) in [ + (MAX_ARGON2_MEMORY_BYTES + 1, 1, 1), + (128 * 1024 * 1024, MAX_ARGON2_ITERATIONS + 1, 1), + (128 * 1024 * 1024, 1, MAX_ARGON2_PARALLELISM + 1), + (2 * 1024 * 1024 * 1024, 8, 4), // within per-field caps, over the work cap + ] { + let bytes = kdbx4_header(argon2_dictionary( + VARIANT_BYTE_ARRAY, + UUID_ARGON2ID, + memory, + iterations, + parallelism, + )); + assert!( + validate_kdf_cost(&bytes, KdbxVersion::V4_0).is_err(), + "memory={memory} iterations={iterations} parallelism={parallelism} must be rejected" + ); + } + } + + #[test] + fn normal_aes_kdf_in_kdbx4_passes() { + let dictionary = aes_dictionary(VARIANT_BYTE_ARRAY, 600_000); + assert!(validate_kdf_cost(&kdbx4_header(dictionary), KdbxVersion::V4_0).is_ok()); + } + + #[test] + fn byte_array_kdf_with_extreme_aes_rounds_is_rejected() { + // Legal KDBX 4 stores `$UUID` as a ByteArray (0x42). Before the fix + // this file was not recognised and the AES-KDF limit was skipped. + let dictionary = aes_dictionary(VARIANT_BYTE_ARRAY, 30_000_000); + let error = validate_kdf_cost(&kdbx4_header(dictionary), KdbxVersion::V4_0) + .expect_err("a 30M-round ByteArray KDF must be rejected"); + assert!(matches!(error, KdbxReadError::Unsupported(_))); + } + + #[test] + fn legacy_int32_uuid_is_still_validated() { + let dictionary = aes_dictionary(VARIANT_INT32, 30_000_000); + let error = validate_kdf_cost(&kdbx4_header(dictionary), KdbxVersion::V4_0) + .expect_err("the legacy 0x0C shape must be validated too"); + assert!(matches!(error, KdbxReadError::Unsupported(_))); + } + + #[test] + fn duplicate_kdbx4_kdf_fields_are_rejected() { + let first = aes_dictionary(VARIANT_BYTE_ARRAY, 600_000); + let second = aes_dictionary(VARIANT_BYTE_ARRAY, 30_000_000); + let bytes = kdbx4_header_with_dictionaries(&[first, second]); + let error = validate_kdf_cost(&bytes, KdbxVersion::V4_0) + .expect_err("duplicate KDF-fields must not be validated selectively"); + assert!(matches!(error, KdbxReadError::Header(_))); + } + + #[test] + fn real_kdbx4_fixture_headers_pass_validation() { + for name in [ + "test_db_kdbx4_with_password_aes.kdbx", + "test_db_kdbx4_with_password_argon2id.kdbx", + "test_db_kdbx41_with_password_aes.kdbx", + ] { + let bytes = fixture(name); + assert!( + validate_kdf_cost(&bytes, KdbxVersion::V4_0).is_ok(), + "{name} must pass the KDF safety limits" + ); + } + } + + #[test] + fn real_fixture_byte_array_uuid_is_seen_and_extremes_are_rejected() { + let bytes = fixture("test_db_kdbx4_with_password_aes.kdbx"); + let dictionary = kdbx4_kdf_dictionary(&bytes); + // The real header uses 0x42; the validator must parse it (it had only + // accepted 0x0C, so every real database silently bypassed the limit). + validate_kdbx4_kdf_parameters(dictionary).expect("real fixture KDF is normal"); + let mut mutated = dictionary.to_vec(); + set_dictionary_u64(&mut mutated, b"R", 30_000_000); + let error = validate_kdbx4_kdf_parameters(&mutated) + .expect_err("an extreme round count in a real header shape must be rejected"); + assert!(matches!(error, KdbxReadError::Unsupported(_))); + } + + #[test] + fn unknown_kdf_is_left_to_the_reader() { + let dictionary = + variant_dictionary(&[variant_entry(VARIANT_BYTE_ARRAY, b"$UUID", &[0x42; 16])]); + assert!(validate_kdf_cost(&kdbx4_header(dictionary), KdbxVersion::V4_0).is_ok()); + } +} + +#[cfg(test)] +mod meta_default_tests { + use super::meta_from; + use crate::model::{DEFAULT_HISTORY_MAX_ITEMS, DEFAULT_HISTORY_MAX_SIZE}; + + #[test] + fn omitted_meta_elements_use_keepass_defaults() { + let meta = keepass::db::Meta { + recyclebin_enabled: None, + history_max_items: None, + history_max_size: None, + ..keepass::db::Meta::default() + }; + let mapped = meta_from(&meta, &keepass::Database::new()); + assert!(mapped.recycle_bin_enabled); + assert_eq!(mapped.history_max_items, DEFAULT_HISTORY_MAX_ITEMS); + assert_eq!(mapped.history_max_size, DEFAULT_HISTORY_MAX_SIZE); + } + + #[test] + fn explicit_meta_limits_are_preserved() { + let meta = keepass::db::Meta { + recyclebin_enabled: Some(false), + history_max_items: Some(0), + history_max_size: Some(-1), + ..keepass::db::Meta::default() + }; + let mapped = meta_from(&meta, &keepass::Database::new()); + assert!(!mapped.recycle_bin_enabled); + assert_eq!(mapped.history_max_items, 0); + assert_eq!(mapped.history_max_size, -1); + } +} + +mod convert; +mod error; +mod header; +mod limits; +mod parse; +mod parser; + +use convert::*; +pub use error::*; +use header::*; +use limits::*; +pub use parse::*; +use parser::*; diff --git a/crates/core/src/kdbx/reader/parse.rs b/crates/core/src/kdbx/reader/parse.rs new file mode 100644 index 0000000..92cd056 --- /dev/null +++ b/crates/core/src/kdbx/reader/parse.rs @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! The public read entry point. + +use super::*; + +/// Parse a KDBX byte buffer into the core model. +/// +/// * `password` is used only to derive the key; it never enters errors/dumps. +/// * The returned model keeps `raw_xml` (not serialized) and its SHA-256 so +/// unknown data can be preserved without leaking plaintext XML in dumps. +pub fn parse(bytes: &[u8], password: &str) -> Result { + let header = bytes + .get(..12) + .ok_or_else(|| KdbxReadError::Header("shorter than 12 bytes".to_string()))?; + let version = detect_version(header).map_err(|error| match error { + crate::kdbx::KdbxHeaderError::TooShort => { + KdbxReadError::Corrupt("header shorter than 12 bytes".to_string()) + } + crate::kdbx::KdbxHeaderError::BadSignature => { + KdbxReadError::Corrupt("not a KDBX file (bad signature)".to_string()) + } + crate::kdbx::KdbxHeaderError::UnknownVersion(version) => { + KdbxReadError::Unsupported(format!("unknown KDBX version word 0x{version:08X}")) + } + })?; + + validate_kdf_cost(bytes, version)?; + let kp = open_with_keepass(bytes, password)?; + let xml = xml_with_keepass(bytes, password)?; + let xml_hash = { + let digest = Sha256::digest(&xml); + let mut out = String::with_capacity(digest.len() * 2); + for byte in digest { + out.push_str(&format!("{byte:02x}")); + } + out + }; + + let meta = meta_from(&kp.meta, &kp); + let root = group_from(&kp.root(), &kp); + let outer = parse_outer_header(bytes, version); + + let mut deleted_objects: Vec = kp + .deleted_objects + .iter() + .map(|(uuid, time)| DeletedObject { + uuid: uuid_from_display(uuid), + deletion_time: time.map(format_time).unwrap_or_default(), + }) + .collect(); + deleted_objects.sort_by_key(|a| a.uuid); + + Ok(Database { + format_version: version.as_str().to_string(), + outer, + meta, + root, + deleted_objects, + unknown: Vec::new(), + raw_xml: Some(xml), + raw_xml_sha256: Some(xml_hash), + }) +} diff --git a/crates/core/src/kdbx/reader/parser.rs b/crates/core/src/kdbx/reader/parser.rs new file mode 100644 index 0000000..e113868 --- /dev/null +++ b/crates/core/src/kdbx/reader/parser.rs @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! The bridge into the vendored keepass parser. + +use super::*; + +pub(crate) fn open_with_keepass(bytes: &[u8], password: &str) -> Result { + guard_keepass(|| { + let mut cursor = Cursor::new(bytes); + let key = DatabaseKey::new().with_password(password); + KpDatabase::open(&mut cursor, key) + }) +} + +pub(crate) fn xml_with_keepass(bytes: &[u8], password: &str) -> Result, KdbxReadError> { + guard_keepass(|| { + let mut cursor = Cursor::new(bytes); + let key = DatabaseKey::new().with_password(password); + KpDatabase::get_xml(&mut cursor, key) + }) +} diff --git a/crates/core/src/kdbx/writer.rs b/crates/core/src/kdbx/writer.rs deleted file mode 100644 index c93cf4c..0000000 --- a/crates/core/src/kdbx/writer.rs +++ /dev/null @@ -1,269 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-or-later -//! KDBX writer: re-encrypt an existing KDBX byte buffer through the vendored -//! keepassxcr backend. -//! -//! The backend derives a fresh KDF salt, master seed and encryption IV on every -//! save, and preserves unknown XML because it round-trips the whole database -//! model. This module is IO-free: callers pass bytes and receive bytes. -//! -//! Full model-to-database writing (edits, attachments, merges) is M1-04+ work; -//! this task establishes the byte-level write path and its verification. - -use crate::kdbx::detect_version; -use crate::model::{Database, Entry, Group, Times, Uuid}; -use keepassxcr::format::{read_kdbx_bytes, write_kdbx_bytes}; -use keepassxcr::model::{ - Attachment as BackendAttachment, Database as BackendDatabase, - DeletedObject as BackendDeletedObject, Entry as BackendEntry, Group as BackendGroup, - HistoryLimits as BackendHistoryLimits, Times as BackendTimes, Timestamp, -}; -use keepassxcr::Credentials; -use std::fmt; - -/// Write backend identity (also exposed in diagnostics). -pub const WRITE_BACKEND: &str = "keepassxcr 0.3.1 (vendored, byte API)"; - -/// Default output version for newly created databases. -pub const DEFAULT_WRITE_VERSION: &str = "4.0"; - -/// Error returned by the KDBX writer. -#[derive(Debug)] -pub enum KdbxWriteError { - /// Header missing/unsupported. - Header(String), - /// Input could not be decrypted. - Read(String), - /// Output could not be encrypted. - Write(String), -} - -impl fmt::Display for KdbxWriteError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Header(message) => write!(f, "invalid KDBX header: {message}"), - Self::Read(message) => write!(f, "cannot read KDBX: {message}"), - Self::Write(message) => write!(f, "cannot write KDBX: {message}"), - } - } -} - -impl std::error::Error for KdbxWriteError {} - -/// Re-encrypt `bytes` (same database contents) with the selected backend. -/// -/// A fresh KDF salt, master seed and IV are generated by the backend on every -/// call, so two calls on the same input produce different bytes. The format -/// version is preserved (M1-03 default-write policy for new empty databases is -/// `DEFAULT_WRITE_VERSION`; version upgrades are a separate operation). -pub fn reseal(bytes: &[u8], password: &str) -> Result, KdbxWriteError> { - let header = bytes - .get(..12) - .ok_or_else(|| KdbxWriteError::Header("shorter than 12 bytes".to_string()))?; - detect_version(header).map_err(|error| KdbxWriteError::Header(error.to_string()))?; - if password.is_empty() { - return Err(KdbxWriteError::Read( - "password required to re-encrypt".to_string(), - )); - } - - let credentials = Credentials::password(password); - let file = read_kdbx_bytes(bytes, &credentials) - .map_err(|error| KdbxWriteError::Read(format!("{error:?}")))?; - write_kdbx_bytes(&file, &credentials) - .map_err(|error| KdbxWriteError::Write(format!("{error:?}"))) -} - -/// Serialise the core model to a new KDBX 4.0 file. -/// -/// This is the write bridge used after merge/edit operations. The current -/// mapping is intentionally limited to the data needed by the merge path -/// (UUID/name/fields/tags/times/history/attachments/DeletedObjects); unknown -/// raw XML, auto-type, icons and custom icons are not yet mapped, so callers -/// must not treat this as a full-fidelity rewrite of arbitrary databases. -pub fn write_model(db: &Database, password: &str) -> Result, KdbxWriteError> { - if password.is_empty() { - return Err(KdbxWriteError::Write( - "password required to encrypt".to_string(), - )); - } - let backend = to_backend(db); - let file = keepassxcr::KdbxFile::new(backend); - let credentials = Credentials::password(password); - write_kdbx_bytes(&file, &credentials) - .map_err(|error| KdbxWriteError::Write(format!("{error:?}"))) -} - -/// Create a new empty KDBX 4.0 database with a `General` root group. -/// -/// This is intentionally a small, IO-free bridge for the app's "new database" -/// flow. It uses the same backend and version policy as [`write_model`]. -pub fn create_empty(name: &str, password: &str) -> Result, KdbxWriteError> { - if password.is_empty() { - return Err(KdbxWriteError::Write( - "password required to encrypt".to_string(), - )); - } - let database_name = if name.trim().is_empty() { - "keepassity".to_string() - } else { - name.trim().to_string() - }; - let mut backend = BackendDatabase::new(database_name); - backend.root_mut().set_name("General".to_string()); - let file = keepassxcr::KdbxFile::new(backend); - let credentials = Credentials::password(password); - write_kdbx_bytes(&file, &credentials) - .map_err(|error| KdbxWriteError::Write(format!("{error:?}"))) -} - -fn backend_uuid(uuid: Uuid) -> keepassxcr::Uuid { - keepassxcr::Uuid::from_bytes(*uuid.as_bytes()) -} - -fn backend_timestamp(text: &str) -> Timestamp { - Timestamp::parse(text).unwrap_or_else(Timestamp::now) -} - -fn backend_times(times: &Times) -> BackendTimes { - BackendTimes { - creation: backend_timestamp(×.creation), - last_modification: backend_timestamp(×.last_modification), - last_access: backend_timestamp(×.last_access), - expiry: backend_timestamp(×.expiry), - expires: times.expires, - usage_count: times.usage_count, - location_changed: backend_timestamp(×.location_changed), - } -} - -fn to_backend(db: &Database) -> BackendDatabase { - let name = if db.meta.database_name.is_empty() { - "keepassity".to_string() - } else { - db.meta.database_name.clone() - }; - let mut backend = BackendDatabase::new(name); - backend - .meta_mut() - .set_description(db.meta.database_description.clone()); - backend - .meta_mut() - .set_recycle_bin_enabled(db.meta.recycle_bin_enabled); - backend.meta_mut().set_history_limits(BackendHistoryLimits { - max_items: db - .meta - .history_max_items - .clamp(i32::MIN as i64, i32::MAX as i64) as i32, - max_size: db.meta.history_max_size, - }); - if let Some(uuid) = db.meta.recycle_bin_uuid { - backend - .meta_mut() - .load_recycle_bin(Some(backend_uuid(uuid)), Timestamp::now()); - } - for item in &db.deleted_objects { - backend.deleted_objects_mut().push(BackendDeletedObject { - uuid: backend_uuid(item.uuid), - deletion_time: backend_timestamp(&item.deletion_time), - }); - } - let root = backend.root_mut(); - fill_backend_group(root, &db.root); - backend -} - -fn fill_backend_group(backend: &mut BackendGroup, group: &Group) { - backend.set_uuid(backend_uuid(group.uuid)); - backend.set_name(group.name.clone()); - backend.set_tags(group.tags.join(";")); - *backend.times_mut() = backend_times(&group.times); - backend.set_previous_parent_group(group.previous_parent_group.map(backend_uuid)); - for entry in &group.entries { - backend.entries_mut().push(to_backend_entry(entry)); - } - for child in &group.groups { - let mut target = BackendGroup::with_uuid(backend_uuid(child.uuid), child.name.clone()); - fill_backend_group(&mut target, child); - backend.groups_mut().push(target); - } -} - -fn to_backend_entry(entry: &Entry) -> BackendEntry { - let mut backend = BackendEntry::with_uuid( - backend_uuid(entry.uuid), - entry.field("Title").unwrap_or("").to_string(), - ); - backend.set_username(entry.field("UserName").unwrap_or("").to_string()); - backend.set_password(entry.field("Password").unwrap_or("").to_string().into()); - backend.set_url(entry.field("URL").unwrap_or("").to_string()); - backend.set_notes(entry.field("Notes").unwrap_or("").to_string()); - backend.set_tags(&entry.tags.join(";")); - *backend.times_mut() = backend_times(&entry.times); - backend.set_previous_parent_group(entry.previous_parent_group.map(backend_uuid)); - for field in &entry.strings { - if matches!( - field.key.as_str(), - "Title" | "UserName" | "Password" | "URL" | "Notes" - ) { - continue; - } - backend.set_custom_field(field.key.clone(), field.value.clone(), field.protected); - } - for binary in &entry.binaries { - backend - .attachments_mut() - .push(BackendAttachment::with_protection( - binary.key.clone(), - binary.value.clone(), - binary.protected, - )); - } - for history in &entry.history { - backend.history_mut().push(to_backend_entry(history)); - } - backend -} - -/// Version that the backend uses for `KdbxFile::new` (new databases). -pub fn new_database_version() -> &'static str { - match keepassxcr::KdbxFile::new(keepassxcr::Database::new("keepassity".into())).version { - keepassxcr::format::KdbxVersion::V4_0 => "4.0", - keepassxcr::format::KdbxVersion::V4_1 => "4.1", - keepassxcr::format::KdbxVersion::V3_1 => "3.1", - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn backend_default_version_is_4_0() { - assert_eq!(new_database_version(), DEFAULT_WRITE_VERSION); - } - - #[test] - fn rejects_truncated_input() { - assert!(matches!( - reseal(&[0u8; 4], "x"), - Err(KdbxWriteError::Header(_)) - )); - } - - #[test] - fn creates_empty_database_that_reads_back() { - let bytes = create_empty("Fresh", "correct horse battery staple").unwrap(); - let credentials = Credentials::password("correct horse battery staple"); - let file = read_kdbx_bytes(&bytes, &credentials).unwrap(); - assert_eq!(file.database.root().name(), "General"); - assert!(file.database.root().entries().is_empty()); - } - - #[test] - fn create_empty_rejects_empty_password() { - assert!(matches!( - create_empty("Fresh", ""), - Err(KdbxWriteError::Write(_)) - )); - } -} diff --git a/crates/core/src/kdbx/writer/backend.rs b/crates/core/src/kdbx/writer/backend.rs new file mode 100644 index 0000000..dca8af4 --- /dev/null +++ b/crates/core/src/kdbx/writer/backend.rs @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Converting the core model into the backend types. + +use super::*; + +pub(crate) fn backend_uuid(uuid: Uuid) -> keepassxcr::Uuid { + keepassxcr::Uuid::from_bytes(*uuid.as_bytes()) +} + +pub(crate) fn backend_timestamp(text: &str) -> Timestamp { + Timestamp::parse(text).unwrap_or_else(Timestamp::now) +} + +pub(crate) fn backend_times(times: &Times) -> BackendTimes { + BackendTimes { + creation: backend_timestamp(×.creation), + last_modification: backend_timestamp(×.last_modification), + last_access: backend_timestamp(×.last_access), + expiry: backend_timestamp(×.expiry), + expires: times.expires, + usage_count: times.usage_count, + location_changed: backend_timestamp(×.location_changed), + } +} + +pub(crate) fn to_backend(db: &Database) -> BackendDatabase { + let name = if db.meta.database_name.is_empty() { + "keepassity".to_string() + } else { + db.meta.database_name.clone() + }; + let mut backend = BackendDatabase::new(name); + backend + .meta_mut() + .set_description(db.meta.database_description.clone()); + backend + .meta_mut() + .set_recycle_bin_enabled(db.meta.recycle_bin_enabled); + backend.meta_mut().set_history_limits(BackendHistoryLimits { + max_items: db + .meta + .history_max_items + .clamp(i32::MIN as i64, i32::MAX as i64) as i32, + max_size: db.meta.history_max_size, + }); + for extra in meta_extra(&db.meta) { + backend.meta_mut().extra_mut().push(extra); + } + for icon in &db.meta.custom_icons { + backend + .meta_mut() + .custom_icons_mut() + .push(custom_icon_element(icon)); + } + if let Some(uuid) = db.meta.recycle_bin_uuid { + let changed = db + .meta + .recycle_bin_changed + .as_deref() + .filter(|text| !text.is_empty()) + .map(backend_timestamp) + .unwrap_or_else(Timestamp::now); + backend + .meta_mut() + .load_recycle_bin(Some(backend_uuid(uuid)), changed); + } + for item in &db.deleted_objects { + backend.deleted_objects_mut().push(BackendDeletedObject { + uuid: backend_uuid(item.uuid), + deletion_time: backend_timestamp(&item.deletion_time), + }); + } + let root = backend.root_mut(); + fill_backend_group(root, &db.root); + backend +} + +pub(crate) fn fill_backend_group(backend: &mut BackendGroup, group: &Group) { + backend.set_uuid(backend_uuid(group.uuid)); + backend.set_name(group.name.clone()); + backend.set_tags(group.tags.join(";")); + *backend.times_mut() = backend_times(&group.times); + backend.set_previous_parent_group(group.previous_parent_group.map(backend_uuid)); + for extra in group_extra(group) { + backend.extra_mut().push(extra); + } + for entry in &group.entries { + backend.entries_mut().push(to_backend_entry(entry)); + } + for child in &group.groups { + let mut target = BackendGroup::with_uuid(backend_uuid(child.uuid), child.name.clone()); + fill_backend_group(&mut target, child); + backend.groups_mut().push(target); + } +} + +pub(crate) fn to_backend_entry(entry: &Entry) -> BackendEntry { + let mut backend = BackendEntry::with_uuid( + backend_uuid(entry.uuid), + entry.field("Title").unwrap_or("").to_string(), + ); + backend.set_username(entry.field("UserName").unwrap_or("").to_string()); + backend.set_password(entry.field("Password").unwrap_or("").to_string().into()); + backend.set_url(entry.field("URL").unwrap_or("").to_string()); + backend.set_notes(entry.field("Notes").unwrap_or("").to_string()); + backend.set_tags(&entry.tags.join(";")); + *backend.times_mut() = backend_times(&entry.times); + backend.set_previous_parent_group(entry.previous_parent_group.map(backend_uuid)); + for extra in entry_extra(entry) { + backend.extra_mut().push(extra); + } + for field in &entry.strings { + if matches!( + field.key.as_str(), + "Title" | "UserName" | "Password" | "URL" | "Notes" + ) { + if field.protected { + backend.set_protected(&field.key, true); + } + continue; + } + backend.set_custom_field(field.key.clone(), field.value.clone(), field.protected); + } + for binary in &entry.binaries { + backend + .attachments_mut() + .push(BackendAttachment::with_protection( + binary.key.clone(), + binary.value.clone(), + binary.protected, + )); + } + for history in &entry.history { + backend.history_mut().push(to_backend_entry(history)); + } + backend +} diff --git a/crates/core/src/kdbx/writer/create.rs b/crates/core/src/kdbx/writer/create.rs new file mode 100644 index 0000000..107ecaa --- /dev/null +++ b/crates/core/src/kdbx/writer/create.rs @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Creating a new database. + +use super::*; + +/// Create a new empty KDBX 4.0 database with a `General` root group. +/// +/// This is intentionally a small, IO-free bridge for the app's "new database" +/// flow. It uses the same backend and version policy as [`write_model`]. +pub fn create_empty(name: &str, password: &str) -> Result, KdbxWriteError> { + create_empty_with_kdf(name, password, None) +} + +/// Create a new empty KDBX 4.0 database with an explicit KDF. +/// +/// Without `kdf` the backend default applies (the "new database" parameters). +/// With it the header carries exactly those settings, so the caller does not +/// have to write, re-read and re-save a fresh database just to change them. +pub fn create_empty_with_kdf( + name: &str, + password: &str, + kdf: Option, +) -> Result, KdbxWriteError> { + if password.is_empty() { + return Err(KdbxWriteError::Write( + "password required to encrypt".to_string(), + )); + } + if let Some(kdf) = kdf.as_ref() { + kdf.validate() + .map_err(|error| KdbxWriteError::Write(error.to_string()))?; + } + let database_name = if name.trim().is_empty() { + "keepassity".to_string() + } else { + name.trim().to_string() + }; + let mut backend = BackendDatabase::new(database_name); + backend.root_mut().set_name("General".to_string()); + let mut file = keepassxcr::KdbxFile::new(backend); + if let Some(kdf) = kdf { + file.kdf = backend_kdf(&kdf); + } + let credentials = Credentials::password(password); + write_kdbx_bytes(&file, &credentials) + .map_err(|error| KdbxWriteError::Write(format!("{error:?}"))) +} + +/// Version that the backend uses for `KdbxFile::new` (new databases). +pub fn new_database_version() -> &'static str { + match keepassxcr::KdbxFile::new(keepassxcr::Database::new("keepassity".into())).version { + keepassxcr::format::KdbxVersion::V4_0 => "4.0", + keepassxcr::format::KdbxVersion::V4_1 => "4.1", + keepassxcr::format::KdbxVersion::V3_1 => "3.1", + } +} diff --git a/crates/core/src/kdbx/writer/mod.rs b/crates/core/src/kdbx/writer/mod.rs new file mode 100644 index 0000000..0d7051f --- /dev/null +++ b/crates/core/src/kdbx/writer/mod.rs @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! KDBX writer: re-encrypt an existing KDBX byte buffer through the vendored +//! keepassxcr backend. +//! +//! The backend derives a fresh KDF salt, master seed and encryption IV on every +//! save, and preserves unknown XML because it round-trips the whole database +//! model. This module is IO-free: callers pass bytes and receive bytes. +//! +//! Full model-to-database writing (edits, attachments, merges) is M1-04+ work; +//! this task establishes the byte-level write path and its verification. + +use crate::kdbx::detect_version; +use crate::model::{ + Argon2Kind, AutoType, CustomData, CustomDataValue, CustomIcon, Database, Entry, Group, + KdfSettings, Meta, OuterCipher, OuterCompression, Times, Uuid, +}; +use keepassxcr::crypto::{CipherId, KdfConfig, KdfType}; +use keepassxcr::format::{ + read_kdbx_bytes, write_kdbx_bytes, write_kdbx_bytes_with_cache, Compression, KdbxVersion, +}; +use keepassxcr::model::{ + Attachment as BackendAttachment, Database as BackendDatabase, + DeletedObject as BackendDeletedObject, Entry as BackendEntry, Group as BackendGroup, + HistoryLimits as BackendHistoryLimits, RawElement, Times as BackendTimes, Timestamp, +}; +use keepassxcr::Credentials; +use std::fmt; + +pub use keepassxcr::format::KdfCache; + +/// Write backend identity (also exposed in diagnostics). +pub const WRITE_BACKEND: &str = "keepassxcr 0.3.1 (vendored, byte API)"; + +/// Default output version for newly created databases. +pub const DEFAULT_WRITE_VERSION: &str = "4.0"; + +/// Error returned by the KDBX writer. +#[derive(Debug)] +pub enum KdbxWriteError { + /// Header missing/unsupported. + Header(String), + /// Input could not be decrypted. + Read(String), + /// Output could not be encrypted. + Write(String), +} + +impl fmt::Display for KdbxWriteError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Header(message) => write!(f, "invalid KDBX header: {message}"), + Self::Read(message) => write!(f, "cannot read KDBX: {message}"), + Self::Write(message) => write!(f, "cannot write KDBX: {message}"), + } + } +} + +impl std::error::Error for KdbxWriteError {} + +mod backend; +mod create; +mod save; +mod xml; + +// Re-exported so the public paths stay exactly what they were when this was one +// file: crate::kdbx::writer::. +use backend::*; +pub use create::*; +pub use save::*; +use xml::*; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn backend_default_version_is_4_0() { + assert_eq!(new_database_version(), DEFAULT_WRITE_VERSION); + } + + #[test] + fn rejects_truncated_input() { + assert!(matches!( + reseal(&[0u8; 4], "x"), + Err(KdbxWriteError::Header(_)) + )); + } + + #[test] + fn creates_empty_database_that_reads_back() { + let bytes = create_empty("Fresh", "correct horse battery staple").unwrap(); + let credentials = Credentials::password("correct horse battery staple"); + let file = read_kdbx_bytes(&bytes, &credentials).unwrap(); + assert_eq!(file.database.root().name(), "General"); + assert!(file.database.root().entries().is_empty()); + } + + #[test] + fn create_empty_rejects_empty_password() { + assert!(matches!( + create_empty("Fresh", ""), + Err(KdbxWriteError::Write(_)) + )); + } +} diff --git a/crates/core/src/kdbx/writer/save.rs b/crates/core/src/kdbx/writer/save.rs new file mode 100644 index 0000000..01bafd0 --- /dev/null +++ b/crates/core/src/kdbx/writer/save.rs @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Saving a model: reseal, the cached-KDF path and write verification. + +use super::*; + +/// Re-encrypt `bytes` (same database contents) with the selected backend. +/// +/// A fresh KDF salt, master seed and IV are generated by the backend on every +/// call, so two calls on the same input produce different bytes. The format +/// version is preserved (M1-03 default-write policy for new empty databases is +/// `DEFAULT_WRITE_VERSION`; version upgrades are a separate operation). +pub fn reseal(bytes: &[u8], password: &str) -> Result, KdbxWriteError> { + let header = bytes + .get(..12) + .ok_or_else(|| KdbxWriteError::Header("shorter than 12 bytes".to_string()))?; + detect_version(header).map_err(|error| KdbxWriteError::Header(error.to_string()))?; + if password.is_empty() { + return Err(KdbxWriteError::Read( + "password required to re-encrypt".to_string(), + )); + } + + let credentials = Credentials::password(password); + let file = read_kdbx_bytes(bytes, &credentials) + .map_err(|error| KdbxWriteError::Read(format!("{error:?}")))?; + write_kdbx_bytes(&file, &credentials) + .map_err(|error| KdbxWriteError::Write(format!("{error:?}"))) +} + +/// Serialise the core model to a KDBX 4.0 file. +/// +/// This is the write bridge used after merge/edit operations. It maps every +/// field the reader produces: UUIDs, standard and custom fields (including +/// their protection flags), tags, times, history, attachments, DeletedObjects, +/// built-in and custom icons, AutoType settings, colors, override URLs, custom +/// data, and the meta fields (description, default user name, memory +/// protection, custom data, custom icons, recycle bin, history limits). Unknown +/// raw XML outside the model is not carried over. +pub fn write_model(db: &Database, password: &str) -> Result, KdbxWriteError> { + write_model_cached(db, password, None).map(|(bytes, _)| bytes) +} + +/// Write `db`, reusing the transformed KDF key in `cache` when provided. The +/// caller keeps the returned cache with the unlocked database; the next save +/// then skips the KDF entirely. The first save derives the key and returns the +/// cache, so the app does not pay a second KDF at open time. +pub fn write_model_cached( + db: &Database, + password: &str, + cache: Option<&KdfCache>, +) -> Result<(Vec, KdfCache), KdbxWriteError> { + if password.is_empty() { + return Err(KdbxWriteError::Write( + "password required to encrypt".to_string(), + )); + } + let backend = to_backend(db); + let mut file = keepassxcr::KdbxFile::new(backend); + apply_outer_header(&mut file, db.outer.as_ref()); + if let Some(kdf) = db.outer.as_ref().and_then(|header| header.kdf.as_ref()) { + kdf.validate() + .map_err(|error| KdbxWriteError::Write(error.to_string()))?; + } + // The backend takes the KDF from the cache, not from `file.kdf`. Drop a + // cache that belongs to different parameters, otherwise changing the KDF + // would silently keep writing the old one. + let cache = cache.filter(|cache| cache_matches_header(db, cache)); + let credentials = Credentials::password(password); + write_kdbx_bytes_with_cache(&file, &credentials, cache) + .map_err(|error| KdbxWriteError::Write(format!("{error:?}"))) +} + +/// Does `cache` belong to the KDF the model is about to write? +/// +/// Without header information there is nothing to compare against, so the cache +/// keeps its previous meaning. +pub(crate) fn cache_matches_header(db: &Database, cache: &KdfCache) -> bool { + match db.outer.as_ref().and_then(|header| header.kdf.as_ref()) { + Some(kdf) => kdf_matches_config(kdf, cache.kdf()), + None => true, + } +} + +pub(crate) fn kdf_matches_config(kdf: &KdfSettings, config: &KdfConfig) -> bool { + match (kdf, config) { + (KdfSettings::Aes { rounds }, KdfConfig::Aes { rounds: cached, .. }) => rounds == cached, + ( + KdfSettings::Argon2 { + kind, + iterations, + memory_kib, + parallelism, + version, + }, + KdfConfig::Argon2 { + kind: cached_kind, + iterations: cached_iterations, + memory_kib: cached_memory, + parallelism: cached_parallelism, + version: cached_version, + .. + }, + ) => { + let same_kind = matches!( + (kind, cached_kind), + (Argon2Kind::D, KdfType::Argon2d) | (Argon2Kind::Id, KdfType::Argon2id) + ); + same_kind + && iterations == cached_iterations + && memory_kib == cached_memory + && parallelism == cached_parallelism + && version == cached_version + } + _ => false, + } +} + +/// Verify that freshly written bytes decrypt and parse. With the save's KDF +/// cache this costs a decrypt, not another Argon2/AES-KDF run, so the save path +/// can refuse to hand corrupt bytes to the file writer. +pub fn verify_written_with_cache( + bytes: &[u8], + password: &str, + cache: &KdfCache, +) -> Result<(), KdbxWriteError> { + let credentials = Credentials::password(password); + keepassxcr::format::read_kdbx_bytes_with_cache(bytes, &credentials, Some(cache)) + .map(|_| ()) + .map_err(|error| KdbxWriteError::Read(format!("{error:?}"))) +} + +/// Carry the source file's outer format settings into the writer. Without this +/// every save rewrote a 4.1 database as 4.0 and replaced the KDF the user (or +/// KeePass) chose with the writer's Argon2id default. Only KDBX4 headers are +/// preserved; a KDBX3 file is still upgraded to the write policy in +/// `DEFAULT_WRITE_VERSION`. +pub(crate) fn apply_outer_header( + file: &mut keepassxcr::KdbxFile, + header: Option<&crate::model::OuterHeader>, +) { + let Some(header) = header else { + return; + }; + file.version = match header.version.as_str() { + "4.1" => KdbxVersion::V4_1, + _ => KdbxVersion::V4_0, + }; + file.cipher = match header.cipher { + OuterCipher::Aes128 => CipherId::Aes128, + OuterCipher::Aes256 => CipherId::Aes256, + OuterCipher::Twofish => CipherId::Twofish, + OuterCipher::ChaCha20 => CipherId::ChaCha20, + }; + file.compression = match header.compression { + OuterCompression::None => Compression::None, + OuterCompression::Gzip => Compression::Gzip, + }; + if let Some(kdf) = &header.kdf { + file.kdf = backend_kdf(kdf); + } + file.public_custom_data = header.public_custom_data.clone(); +} + +/// Map the model's KDF settings to the backend configuration. +/// +/// The writer draws a fresh salt on every save, so only the type and cost are +/// carried over; the placeholder salt is replaced by the backend. +pub(crate) fn backend_kdf(kdf: &KdfSettings) -> KdfConfig { + match kdf { + KdfSettings::Aes { rounds } => KdfConfig::Aes { + seed: vec![0u8; 32], + rounds: *rounds, + legacy: false, + }, + KdfSettings::Argon2 { + kind, + iterations, + memory_kib, + parallelism, + version, + } => KdfConfig::Argon2 { + kind: match kind { + Argon2Kind::D => KdfType::Argon2d, + Argon2Kind::Id => KdfType::Argon2id, + }, + salt: vec![0u8; 32], + iterations: *iterations, + memory_kib: *memory_kib, + parallelism: *parallelism, + version: *version, + }, + } +} diff --git a/crates/core/src/kdbx/writer/xml.rs b/crates/core/src/kdbx/writer/xml.rs new file mode 100644 index 0000000..9db298c --- /dev/null +++ b/crates/core/src/kdbx/writer/xml.rs @@ -0,0 +1,232 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Building the raw XML elements the backend does not model. + +use super::*; + +/// XML text escaping for the raw elements the backend copies verbatim. +pub(crate) fn escape_xml(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for character in text.chars() { + match character { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + other => out.push(other), + } + } + out +} + +pub(crate) fn bool_text(value: bool) -> &'static str { + if value { + "True" + } else { + "False" + } +} + +pub(crate) fn raw_element(name: &str, body: &str) -> RawElement { + RawElement::new(name.to_string(), format!("<{name}>{body}")) +} + +pub(crate) fn simple_element(name: &str, value: &str) -> RawElement { + raw_element(name, &escape_xml(value)) +} + +/// Standard base64 (no line breaks), used for KDBX UUIDs and custom icon data. +pub(crate) fn base64_encode(bytes: &[u8]) -> String { + const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); + for chunk in bytes.chunks(3) { + let first = chunk[0]; + let second = chunk.get(1).copied().unwrap_or(0); + let third = chunk.get(2).copied().unwrap_or(0); + let triple = (u32::from(first) << 16) | (u32::from(second) << 8) | u32::from(third); + out.push(ALPHABET[(triple >> 18) as usize & 0x3F] as char); + out.push(ALPHABET[(triple >> 12) as usize & 0x3F] as char); + if chunk.len() > 1 { + out.push(ALPHABET[(triple >> 6) as usize & 0x3F] as char); + } else { + out.push('='); + } + if chunk.len() > 2 { + out.push(ALPHABET[triple as usize & 0x3F] as char); + } else { + out.push('='); + } + } + out +} + +pub(crate) fn uuid_base64(uuid: Uuid) -> String { + base64_encode(uuid.as_bytes()) +} + +/// `` element with every item, or `None` when there is no data. +pub(crate) fn custom_data_element(data: &CustomData) -> Option { + if data.items.is_empty() { + return None; + } + let mut body = String::new(); + for (key, item) in &data.items { + body.push_str(""); + body.push_str(""); + body.push_str(&escape_xml(key)); + body.push_str(""); + match item.value.as_ref() { + Some(CustomDataValue::String(value)) => body.push_str(&escape_xml(value)), + Some(CustomDataValue::Binary(value)) => body.push_str(&base64_encode(value)), + None => {} + } + body.push_str(""); + if let Some(time) = item + .last_modification + .as_deref() + .filter(|time| !time.is_empty()) + { + body.push_str(""); + body.push_str(&escape_xml(time)); + body.push_str(""); + } + body.push_str(""); + } + Some(raw_element("CustomData", &body)) +} + +pub(crate) fn auto_type_element(auto_type: &AutoType) -> RawElement { + let mut body = String::new(); + body.push_str(""); + body.push_str(bool_text(auto_type.enabled)); + body.push_str(""); + body.push_str(if auto_type.data_transfer_obfuscation { + "1" + } else { + "0" + }); + body.push_str(""); + if !auto_type.default_sequence.is_empty() { + body.push_str(""); + body.push_str(&escape_xml(&auto_type.default_sequence)); + body.push_str(""); + } + for association in &auto_type.associations { + body.push_str(""); + body.push_str(&escape_xml(&association.window)); + body.push_str(""); + body.push_str(&escape_xml(&association.keystroke_sequence)); + body.push_str(""); + } + raw_element("AutoType", &body) +} + +/// Raw XML children of an entry that the backend has no typed API for. +pub(crate) fn entry_extra(entry: &Entry) -> Vec { + let mut extra = Vec::new(); + if entry.icon_id != 0 { + extra.push(simple_element("IconID", &entry.icon_id.to_string())); + } + if let Some(uuid) = entry.custom_icon_uuid { + extra.push(simple_element("CustomIconUUID", &uuid_base64(uuid))); + } + if !entry.foreground_color.is_empty() { + extra.push(simple_element("ForegroundColor", &entry.foreground_color)); + } + if !entry.background_color.is_empty() { + extra.push(simple_element("BackgroundColor", &entry.background_color)); + } + if !entry.override_url.is_empty() { + extra.push(simple_element("OverrideURL", &entry.override_url)); + } + if let Some(auto_type) = &entry.auto_type { + extra.push(auto_type_element(auto_type)); + } + if let Some(custom_data) = custom_data_element(&entry.custom_data) { + extra.push(custom_data); + } + extra +} + +/// Raw XML children of a group that the backend has no typed API for. +pub(crate) fn group_extra(group: &Group) -> Vec { + let mut extra = Vec::new(); + if !group.notes.is_empty() { + extra.push(simple_element("Notes", &group.notes)); + } + if group.icon_id != 0 { + extra.push(simple_element("IconID", &group.icon_id.to_string())); + } + if let Some(uuid) = group.custom_icon_uuid { + extra.push(simple_element("CustomIconUUID", &uuid_base64(uuid))); + } + if group.is_expanded { + extra.push(simple_element("IsExpanded", "True")); + } + if !group.default_autotype_sequence.is_empty() { + extra.push(simple_element( + "DefaultAutoTypeSequence", + &group.default_autotype_sequence, + )); + } + if group.enable_auto_type { + extra.push(simple_element("EnableAutoType", "True")); + } + if group.enable_searching { + extra.push(simple_element("EnableSearching", "True")); + } + if let Some(custom_data) = custom_data_element(&group.custom_data) { + extra.push(custom_data); + } + extra +} + +pub(crate) fn custom_icon_element(icon: &CustomIcon) -> RawElement { + let mut body = String::new(); + body.push_str(""); + body.push_str(&uuid_base64(icon.uuid)); + body.push_str(""); + if let Some(name) = icon.name.as_deref().filter(|name| !name.is_empty()) { + body.push_str(""); + body.push_str(&escape_xml(name)); + body.push_str(""); + } + if let Some(time) = icon + .last_modification + .as_deref() + .filter(|time| !time.is_empty()) + { + body.push_str(""); + body.push_str(&escape_xml(time)); + body.push_str(""); + } + body.push_str(""); + body.push_str(&base64_encode(&icon.data)); + body.push_str(""); + raw_element("Icon", &body) +} + +/// Meta fields that keepassxcr only has a typed API for partially; the rest +/// (memory protection, default user name, custom data) go through raw XML. +pub(crate) fn meta_extra(meta: &Meta) -> Vec { + let mut extra = Vec::new(); + if !meta.default_username.is_empty() { + extra.push(simple_element("DefaultUserName", &meta.default_username)); + } + let protection = &meta.memory_protection; + let body = format!( + "{}{}\ + {}{}\ + {}", + bool_text(protection.protect_title), + bool_text(protection.protect_username), + bool_text(protection.protect_password), + bool_text(protection.protect_url), + bool_text(protection.protect_notes), + ); + extra.push(raw_element("MemoryProtection", &body)); + if let Some(custom_data) = custom_data_element(&meta.custom_data) { + extra.push(custom_data); + } + extra +} diff --git a/crates/core/src/merge/choice.rs b/crates/core/src/merge/choice.rs new file mode 100644 index 0000000..0e8ed3a --- /dev/null +++ b/crates/core/src/merge/choice.rs @@ -0,0 +1,269 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Picking a winner between two versions of an entry or a group. + +use super::*; + +pub(crate) fn choose_group<'a>( + left: &'a Group, + right: &'a Group, +) -> (&'a Group, Option<&'a Group>, bool) { + let left_time = timestamp(&left.times.last_modification); + let right_time = timestamp(&right.times.last_modification); + if left_time >= right_time { + (left, Some(right), true) + } else { + (right, Some(left), true) + } +} + +pub(crate) fn choose_parent( + a: &Side, + b: &Side, + parent_from: impl Fn(&Side) -> Option, + times_from: impl Fn(&Side) -> Option<&Times>, + root: Uuid, +) -> Uuid { + let left = parent_from(a); + let right = parent_from(b); + match (left, right) { + (Some(left), Some(right)) => { + let left_time = times_from(a) + .map(|times| timestamp(×.location_changed)) + .unwrap_or(0); + let right_time = times_from(b) + .map(|times| timestamp(×.location_changed)) + .unwrap_or(0); + if right_time > left_time { + right + } else { + left + } + } + (Some(left), None) => left, + (None, Some(right)) => right, + (None, None) => root, + } +} + +pub(crate) fn timestamp(value: &str) -> i64 { + crate::model::xml_datetime_to_unix(value).unwrap_or(i64::MIN) +} + +/// Semantic content of an entry, used for conflict detection. +/// +/// Serialization details that different KeePass clients and our own writer +/// normalise differently must not turn into conflicts: field order, tags order, +/// empty placeholder fields, the `Protected` attribute, and unknown XML. What +/// stays in the fingerprint is the actual content the user can change. +pub(crate) fn fingerprint(entry: &Entry) -> String { + let mut clean = entry.clone(); + clean.history.clear(); + clean.times = Times::default(); + clean.previous_parent_group = None; + clean + .strings + .sort_by(|left, right| left.key.cmp(&right.key)); + clean.strings.retain(|field| !field.value.is_empty()); + for field in &mut clean.strings { + field.protected = false; + } + clean + .binaries + .sort_by(|left, right| left.key.cmp(&right.key)); + clean.tags.sort(); + clean.tags.dedup(); + clean.unknown.clear(); + serde_json::to_string(&clean).unwrap_or_default() +} + +pub(crate) fn group_fingerprint(group: &Group) -> String { + let mut clean = group.clone(); + clean.groups.clear(); + clean.entries.clear(); + clean.times = Times::default(); + clean.previous_parent_group = None; + clean.tags.sort(); + clean.tags.dedup(); + clean.unknown.clear(); + // Expanding a group is a view setting, not content. + clean.is_expanded = false; + serde_json::to_string(&clean).unwrap_or_default() +} + +/// Fields that describe the entry content, ignoring optional metadata that a +/// writer may drop (icons, colors, auto-type, custom data). +pub(crate) fn entry_content_fingerprint(entry: &Entry) -> String { + let mut clean = entry.clone(); + clean.icon_id = 0; + clean.custom_icon_uuid = None; + clean.foreground_color.clear(); + clean.background_color.clear(); + clean.override_url.clear(); + clean.auto_type = None; + clean.custom_data = crate::model::CustomData::default(); + fingerprint(&clean) +} + +pub(crate) fn entry_metadata_score(entry: &Entry) -> usize { + usize::from(entry.icon_id != 0) + + usize::from(entry.custom_icon_uuid.is_some()) + + usize::from(!entry.foreground_color.is_empty()) + + usize::from(!entry.background_color.is_empty()) + + usize::from(!entry.override_url.is_empty()) + + usize::from(entry.auto_type.is_some()) + + entry.custom_data.items.len() +} + +/// True when the metadata present on both sides agrees, so a difference can +/// only mean one side lost optional data. A real metadata edit (both sides have +/// different icons or different auto-type settings) is not compatible. +pub(crate) fn entry_metadata_compatible(left: &Entry, right: &Entry) -> bool { + let optional_equal = |a: &str, b: &str| a.is_empty() || b.is_empty() || a == b; + if !optional_equal(&left.foreground_color, &right.foreground_color) + || !optional_equal(&left.background_color, &right.background_color) + || !optional_equal(&left.override_url, &right.override_url) + { + return false; + } + if left.icon_id != 0 && right.icon_id != 0 && left.icon_id != right.icon_id { + return false; + } + if let (Some(left_icon), Some(right_icon)) = (left.custom_icon_uuid, right.custom_icon_uuid) { + if left_icon != right_icon { + return false; + } + } + if let (Some(left_auto), Some(right_auto)) = (&left.auto_type, &right.auto_type) { + if auto_type_key(left_auto) != auto_type_key(right_auto) { + return false; + } + } + for (key, item) in &left.custom_data.items { + if let Some(other) = right.custom_data.items.get(key) { + if item != other { + return false; + } + } + } + true +} + +pub(crate) fn auto_type_key(auto_type: &AutoType) -> String { + let mut clean = auto_type.clone(); + clean.unknown.clear(); + serde_json::to_string(&clean).unwrap_or_default() +} + +/// Group fields that a writer may drop without touching the content. +pub(crate) fn group_content_key(group: &Group) -> String { + let mut clean = group.clone(); + clean.groups.clear(); + clean.entries.clear(); + clean.notes.clear(); + clean.icon_id = 0; + clean.custom_icon_uuid = None; + clean.is_expanded = false; + clean.default_autotype_sequence.clear(); + clean.enable_auto_type = false; + clean.enable_searching = false; + clean.last_top_visible_entry = None; + clean.custom_data = crate::model::CustomData::default(); + clean.times = Times::default(); + clean.previous_parent_group = None; + clean.unknown.clear(); + clean.tags.sort(); + clean.tags.dedup(); + serde_json::to_string(&clean).unwrap_or_default() +} + +pub(crate) fn group_metadata_score(group: &Group) -> usize { + usize::from(!group.notes.is_empty()) + + usize::from(group.icon_id != 0) + + usize::from(group.custom_icon_uuid.is_some()) + + usize::from(group.is_expanded) + + usize::from(!group.default_autotype_sequence.is_empty()) + + usize::from(group.enable_auto_type) + + usize::from(group.enable_searching) + + group.custom_data.items.len() +} + +pub(crate) fn group_metadata_compatible(left: &Group, right: &Group) -> bool { + if !left.notes.is_empty() && !right.notes.is_empty() && left.notes != right.notes { + return false; + } + if left.icon_id != 0 && right.icon_id != 0 && left.icon_id != right.icon_id { + return false; + } + if let (Some(left_icon), Some(right_icon)) = (left.custom_icon_uuid, right.custom_icon_uuid) { + if left_icon != right_icon { + return false; + } + } + if !left.default_autotype_sequence.is_empty() + && !right.default_autotype_sequence.is_empty() + && left.default_autotype_sequence != right.default_autotype_sequence + { + return false; + } + for (key, item) in &left.custom_data.items { + if let Some(other) = right.custom_data.items.get(key) { + if item != other { + return false; + } + } + } + true +} + +pub(crate) fn entry_diff_fields(left: &Entry, right: &Entry) -> Vec { + let mut fields = BTreeSet::new(); + let mut keys = BTreeSet::new(); + keys.extend(left.strings.iter().map(|field| field.key.clone())); + keys.extend(right.strings.iter().map(|field| field.key.clone())); + for key in keys { + let left_value = left.strings.iter().find(|field| field.key == key); + let right_value = right.strings.iter().find(|field| field.key == key); + if left_value.map(|field| &field.value) != right_value.map(|field| &field.value) + || left_value.map(|field| field.protected) != right_value.map(|field| field.protected) + { + fields.insert(key); + } + } + if left.tags != right.tags { + fields.insert("Tags".to_string()); + } + if left.auto_type != right.auto_type { + fields.insert("AutoType".to_string()); + } + if left.binaries != right.binaries { + fields.insert("Attachments".to_string()); + } + if fields.is_empty() { + fields.insert("".to_string()); + } + fields.into_iter().collect() +} + +pub(crate) fn group_diff_fields(left: &Group, right: &Group) -> Vec { + let mut fields = Vec::new(); + if left.name != right.name { + fields.push("Name".to_string()); + } + if left.notes != right.notes { + fields.push("Notes".to_string()); + } + if left.tags != right.tags { + fields.push("Tags".to_string()); + } + if left.icon_id != right.icon_id { + fields.push("Icon".to_string()); + } + if fields.is_empty() { + fields.push("".to_string()); + } + fields +} + +pub(crate) fn snapshot_eq(left: &Entry, right: &Entry) -> bool { + fingerprint(left) == fingerprint(right) +} diff --git a/crates/core/src/merge/deletion.rs b/crates/core/src/merge/deletion.rs new file mode 100644 index 0000000..8b396ff --- /dev/null +++ b/crates/core/src/merge/deletion.rs @@ -0,0 +1,253 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Deletion resolution: explicit tombstones, inherited group deletions and the +//! per-entry conflict rules that decide whether a deletion wins or loses. + +use super::*; + +pub(crate) fn merge_deleted(local: &Database, remote: &Database) -> Vec { + let mut deleted: Vec = Vec::new(); + for item in local + .deleted_objects + .iter() + .chain(remote.deleted_objects.iter()) + { + match deleted + .iter() + .position(|existing| existing.uuid == item.uuid) + { + Some(index) => { + // A later deletion of the same object supersedes an earlier + // record; the first record keeps its deterministic position. + if timestamp(&item.deletion_time) > timestamp(&deleted[index].deletion_time) { + deleted[index] = item.clone(); + } + } + None => deleted.push(item.clone()), + } + } + deleted +} + +pub(crate) fn latest_deleted(database: &Database, uuid: Uuid) -> Option<&DeletedObject> { + database + .deleted_objects + .iter() + .filter(|item| item.uuid == uuid) + .max_by_key(|item| timestamp(&item.deletion_time)) +} + +/// Carry group deletion times down both trees: an unchanged child of a deleted +/// group is covered by the parent's deletion time, but a child changed later +/// keeps its own (later) modification time and can survive. +pub(crate) fn inherit_group_deletions( + side: &Side, + deletion_times: &BTreeMap, + out: &mut BTreeMap, +) { + pub(crate) fn walk( + side: &Side, + uuid: Uuid, + inherited: Option, + deletion_times: &BTreeMap, + out: &mut BTreeMap, + ) { + let own = deletion_times.get(&uuid).copied(); + let effective = match (inherited, own) { + (Some(inherited), Some(own)) => Some(inherited.max(own)), + (Some(time), None) | (None, Some(time)) => Some(time), + (None, None) => None, + }; + if let Some(time) = effective { + out.entry(uuid) + .and_modify(|known| *known = (*known).max(time)) + .or_insert(time); + } + for child in side.group_order.get(&uuid).into_iter().flatten() { + walk(side, *child, effective, deletion_times, out); + } + } + walk(side, side.root, None, deletion_times, out); +} + +pub(crate) fn latest_entry_time(a: &Side, b: &Side, uuid: Uuid) -> i64 { + let mut latest = i64::MIN; + if let Some(entry) = a.entries.get(&uuid) { + latest = latest.max(timestamp(&entry.times.last_modification)); + } + if let Some(entry) = b.entries.get(&uuid) { + latest = latest.max(timestamp(&entry.times.last_modification)); + } + latest +} + +pub(crate) fn latest_group_time(a: &Side, b: &Side, uuid: Uuid) -> i64 { + let mut latest = i64::MIN; + if let Some(group) = a.groups.get(&uuid) { + latest = latest.max(timestamp(&group.times.last_modification)); + } + if let Some(group) = b.groups.get(&uuid) { + latest = latest.max(timestamp(&group.times.last_modification)); + } + latest +} + +/// The parent group after merging, decided by the latest `LocationChanged`. +/// This mirrors the layout rule used when the entry is attached. +pub(crate) fn choose_entry_parent(a: &Side, b: &Side, uuid: Uuid) -> Option { + let local = a.entry_parent.get(&uuid).copied(); + let remote = b.entry_parent.get(&uuid).copied(); + match (local, remote) { + (Some(local), Some(remote)) => { + let local_time = a + .entries + .get(&uuid) + .map(|entry| timestamp(&entry.times.location_changed)) + .unwrap_or(i64::MIN); + let remote_time = b + .entries + .get(&uuid) + .map(|entry| timestamp(&entry.times.location_changed)) + .unwrap_or(i64::MIN); + if remote_time > local_time { + Some(remote) + } else { + Some(local) + } + } + (Some(local), None) => Some(local), + (None, Some(remote)) => Some(remote), + (None, None) => None, + } +} + +pub(crate) fn has_surviving_content( + a: &Side, + b: &Side, + group: Uuid, + entry_deleted: &BTreeSet, + group_deleted: &BTreeSet, +) -> bool { + [a, b].into_iter().any(|side| { + side.entry_order + .get(&group) + .into_iter() + .flatten() + .any(|uuid| !entry_deleted.contains(uuid)) + || side + .group_order + .get(&group) + .into_iter() + .flatten() + .any(|uuid| !group_deleted.contains(uuid)) + }) +} + +pub(crate) fn entry_deletion_conflict( + uuid: Uuid, + local: Option<&Entry>, + remote: Option<&Entry>, + local_deletion: Option<&DeletedObject>, + remote_deletion: Option<&DeletedObject>, +) -> MergeConflict { + let deleted_remotely = remote_deletion.is_some() && local.is_some() && local_deletion.is_none(); + let deleted_locally = local_deletion.is_some() && remote.is_some() && remote_deletion.is_none(); + let fields = if deleted_remotely { + // A readable trace for the UI/log; never a field value. + vec!["deleted remotely but modified locally".to_string()] + } else if deleted_locally { + vec!["deleted locally but modified remotely".to_string()] + } else { + vec!["modified after deletion".to_string()] + }; + // Show the deletion event on the side that deleted the object and the edit + // time on the side that kept it; a stale copy's timestamp would hide when + // the deletion actually happened. + let local_modified = if deleted_remotely { + local + .map(|entry| entry.times.last_modification.clone()) + .unwrap_or_default() + } else if deleted_locally { + local_deletion + .map(|item| item.deletion_time.clone()) + .unwrap_or_default() + } else { + local + .map(|entry| entry.times.last_modification.clone()) + .or_else(|| local_deletion.map(|item| item.deletion_time.clone())) + .unwrap_or_default() + }; + let remote_modified = if deleted_locally { + remote + .map(|entry| entry.times.last_modification.clone()) + .unwrap_or_default() + } else if deleted_remotely { + remote_deletion + .map(|item| item.deletion_time.clone()) + .unwrap_or_default() + } else { + remote + .map(|entry| entry.times.last_modification.clone()) + .or_else(|| remote_deletion.map(|item| item.deletion_time.clone())) + .unwrap_or_default() + }; + MergeConflict { + uuid, + kind: ConflictKind::Entry, + local_modified, + remote_modified, + fields, + } +} + +pub(crate) fn group_deletion_conflict( + uuid: Uuid, + local: Option<&Group>, + remote: Option<&Group>, + local_deletion: Option<&DeletedObject>, + remote_deletion: Option<&DeletedObject>, +) -> MergeConflict { + let deleted_remotely = remote_deletion.is_some() && local.is_some() && local_deletion.is_none(); + let deleted_locally = local_deletion.is_some() && remote.is_some() && remote_deletion.is_none(); + let fields = if deleted_remotely { + vec!["deleted remotely but modified locally".to_string()] + } else if deleted_locally { + vec!["deleted locally but modified remotely".to_string()] + } else { + vec!["modified after deletion".to_string()] + }; + let local_modified = if deleted_remotely { + local + .map(|group| group.times.last_modification.clone()) + .unwrap_or_default() + } else if deleted_locally { + local_deletion + .map(|item| item.deletion_time.clone()) + .unwrap_or_default() + } else { + local + .map(|group| group.times.last_modification.clone()) + .or_else(|| local_deletion.map(|item| item.deletion_time.clone())) + .unwrap_or_default() + }; + let remote_modified = if deleted_locally { + remote + .map(|group| group.times.last_modification.clone()) + .unwrap_or_default() + } else if deleted_remotely { + remote_deletion + .map(|item| item.deletion_time.clone()) + .unwrap_or_default() + } else { + remote + .map(|group| group.times.last_modification.clone()) + .or_else(|| remote_deletion.map(|item| item.deletion_time.clone())) + .unwrap_or_default() + }; + MergeConflict { + uuid, + kind: ConflictKind::Group, + local_modified, + remote_modified, + fields, + } +} diff --git a/crates/core/src/merge/index.rs b/crates/core/src/merge/index.rs new file mode 100644 index 0000000..ce99626 --- /dev/null +++ b/crates/core/src/merge/index.rs @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Indexing one side of a merge: groups, entries and their parent links. + +use super::*; + +pub(crate) struct Side { + pub(crate) root: Uuid, + pub(crate) groups: BTreeMap, + pub(crate) group_parent: BTreeMap>, + pub(crate) entries: BTreeMap, + pub(crate) entry_parent: BTreeMap, + pub(crate) group_order: BTreeMap>, + pub(crate) entry_order: BTreeMap>, +} + +pub(crate) fn index(db: &Database) -> Side { + let mut side = Side { + root: db.root.uuid, + groups: BTreeMap::new(), + group_parent: BTreeMap::new(), + entries: BTreeMap::new(), + entry_parent: BTreeMap::new(), + group_order: BTreeMap::new(), + entry_order: BTreeMap::new(), + }; + walk(&db.root, None, &mut side); + side +} + +pub(crate) fn walk(group: &Group, parent: Option, side: &mut Side) { + let uuid = group.uuid; + let mut clean = group.clone(); + clean.groups.clear(); + clean.entries.clear(); + side.groups.insert(uuid, clean); + side.group_parent.insert(uuid, parent); + if let Some(parent) = parent { + side.group_order.entry(parent).or_default().push(uuid); + } + for entry in &group.entries { + side.entries.insert(entry.uuid, entry.clone()); + side.entry_parent.insert(entry.uuid, uuid); + side.entry_order.entry(uuid).or_default().push(entry.uuid); + } + for child in &group.groups { + walk(child, Some(uuid), side); + } +} + +pub(crate) fn build_group( + uuid: Uuid, + groups: &BTreeMap, + group_order: &BTreeMap>, + entry_order: &BTreeMap>, + entries: &BTreeMap, + visited: &mut BTreeSet, +) -> Group { + if !visited.insert(uuid) { + let mut group = groups.get(&uuid).cloned().unwrap_or_default(); + group.groups.clear(); + group.entries.clear(); + return group; + } + let mut group = groups.get(&uuid).cloned().unwrap_or_default(); + group.uuid = uuid; + group.groups = group_order + .get(&uuid) + .into_iter() + .flatten() + .map(|child| build_group(*child, groups, group_order, entry_order, entries, visited)) + .collect(); + group.entries = entry_order + .get(&uuid) + .into_iter() + .flatten() + .filter_map(|entry| entries.get(entry).cloned()) + .collect(); + group +} diff --git a/crates/core/src/merge/mod.rs b/crates/core/src/merge/mod.rs index dc7033a..5c97e21 100644 --- a/crates/core/src/merge/mod.rs +++ b/crates/core/src/merge/mod.rs @@ -6,7 +6,7 @@ //! `History`; deleted UUIDs never resurrect; a newer LocationChanged decides //! the parent group. The output is deterministic and does not mutate inputs. -use crate::model::{Database, DeletedObject, Entry, Group, Times, Uuid}; +use crate::model::{AutoType, Database, DeletedObject, Entry, Group, HistoryLimits, Times, Uuid}; use std::collections::{BTreeMap, BTreeSet}; /// What kind of object conflicts. @@ -61,48 +61,132 @@ pub fn merge(local: &Database, remote: &Database) -> (Database, MergeReport) { let a = index(local); let b = index(remote); let mut report = MergeReport::default(); + // The database that receives the merge owns the history retention policy. + let limits = HistoryLimits::from_meta(&local.meta); + + // Deletion records are a union by UUID; when either side has several + // records for the same object, the latest deletion wins. The root group is + // never deletable, even if a corrupt remote says so. + let mut deleted = merge_deleted(local, remote); + deleted.retain(|item| item.uuid != a.root && item.uuid != b.root); + let mut deletion_times: BTreeMap = BTreeMap::new(); + for item in &deleted { + let time = timestamp(&item.deletion_time); + deletion_times + .entry(item.uuid) + .and_modify(|known| *known = (*known).max(time)) + .or_insert(time); + } + + let all_group_uuids: BTreeSet = a.groups.keys().chain(b.groups.keys()).copied().collect(); + let all_entry_uuids: BTreeSet = + a.entries.keys().chain(b.entries.keys()).copied().collect(); + + // A deleted group also covers its subtree. Carry the latest deletion time + // down each side's tree so an unchanged child is removed with its parent, + // while a child changed after the deletion can still survive. + let mut group_deletion_times: BTreeMap = BTreeMap::new(); + inherit_group_deletions(&a, &deletion_times, &mut group_deletion_times); + inherit_group_deletions(&b, &deletion_times, &mut group_deletion_times); + + // Only an object that was not modified after the deletion may be removed. + // A newer local/remote edit wins and is surfaced as a conflict, so the user + // can see that one side deleted data the other side had modified. + let mut entry_deleted: BTreeSet = BTreeSet::new(); + for uuid in &all_entry_uuids { + let modified = latest_entry_time(&a, &b, *uuid); + let parent = choose_entry_parent(&a, &b, *uuid); + let own = deletion_times.get(uuid).copied(); + let inherited = parent + .and_then(|parent| group_deletion_times.get(&parent)) + .copied(); + let effective = match (own, inherited) { + (Some(own), Some(inherited)) => Some(own.max(inherited)), + (Some(time), None) | (None, Some(time)) => Some(time), + (None, None) => None, + }; + let Some(effective) = effective else { + continue; + }; + if modified <= effective { + entry_deleted.insert(*uuid); + report.deleted_skipped += 1; + continue; + } + if own.is_some() { + report.conflicts += 1; + report.conflict_items.push(entry_deletion_conflict( + *uuid, + a.entries.get(uuid), + b.entries.get(uuid), + latest_deleted(local, *uuid), + latest_deleted(remote, *uuid), + )); + } + } - let deleted = merge_deleted(local, remote); - let deleted_uuids: BTreeSet = deleted.iter().map(|item| item.uuid).collect(); - let mut deleted_groups = BTreeSet::new(); - // A deleted group deletes its whole subtree (cannot resurrect descendants). + // Groups are decided to a fixed point, deepest last: a group can only be + // deleted when nothing inside it survives (a newer entry, a newer subgroup, + // or a subgroup that itself still has content). + let mut group_deleted: BTreeSet = BTreeSet::new(); + let mut group_deletable: BTreeSet = BTreeSet::new(); + for uuid in &all_group_uuids { + if *uuid == a.root || *uuid == b.root { + continue; + } + let Some(effective) = group_deletion_times.get(uuid).copied() else { + continue; + }; + let modified = latest_group_time(&a, &b, *uuid); + if modified <= effective { + group_deletable.insert(*uuid); + } else if deletion_times.contains_key(uuid) { + report.conflicts += 1; + report.conflict_items.push(group_deletion_conflict( + *uuid, + a.groups.get(uuid), + b.groups.get(uuid), + latest_deleted(local, *uuid), + latest_deleted(remote, *uuid), + )); + } + } loop { let mut changed = false; - for uuid in a.groups.keys().chain(b.groups.keys()) { - if deleted_groups.contains(uuid) { + for uuid in &all_group_uuids { + if group_deleted.contains(uuid) || !group_deletable.contains(uuid) { continue; } - let parent = parent_of_group(&a, &b, *uuid); - if parent.is_some_and(|parent| { - deleted_uuids.contains(&parent) || deleted_groups.contains(&parent) - }) { - deleted_groups.insert(*uuid); - changed = true; - } - } - for uuid in deleted_uuids - .iter() - .filter(|uuid| a.groups.contains_key(uuid) || b.groups.contains_key(uuid)) - { - if deleted_groups.insert(*uuid) { - changed = true; + if has_surviving_content(&a, &b, *uuid, &entry_deleted, &group_deleted) { + continue; } + group_deleted.insert(*uuid); + report.deleted_skipped += 1; + changed = true; } if !changed { break; } } - let all_group_uuids: BTreeSet = a.groups.keys().chain(b.groups.keys()).copied().collect(); - let all_entry_uuids: BTreeSet = - a.entries.keys().chain(b.entries.keys()).copied().collect(); + // A deletion record for a live object was not applied (newer edit or + // surviving content); drop it. Records for objects that are gone stay, so a + // stale copy cannot resurrect them. + deleted.retain(|item| { + if entry_deleted.contains(&item.uuid) || group_deleted.contains(&item.uuid) { + return true; + } + !(a.entries.contains_key(&item.uuid) + || b.entries.contains_key(&item.uuid) + || a.groups.contains_key(&item.uuid) + || b.groups.contains_key(&item.uuid)) + }); let root = a.root; let mut merged_groups: BTreeMap = BTreeMap::new(); let mut group_parent: BTreeMap = BTreeMap::new(); for uuid in &all_group_uuids { - if deleted_groups.contains(uuid) { - report.deleted_skipped += 1; + if group_deleted.contains(uuid) { continue; } let (winner, other, both) = match (a.groups.get(uuid), b.groups.get(uuid)) { @@ -121,7 +205,7 @@ pub fn merge(local: &Database, remote: &Database) -> (Database, MergeReport) { |side| side.groups.get(uuid).map(|group| &group.times), root, ); - let parent = if deleted_groups.contains(&parent) || !all_group_uuids.contains(&parent) { + let parent = if group_deleted.contains(&parent) || !all_group_uuids.contains(&parent) { root } else { parent @@ -142,14 +226,31 @@ pub fn merge(local: &Database, remote: &Database) -> (Database, MergeReport) { == timestamp(&right.times.last_modification) && group_fingerprint(left) != group_fingerprint(right) { - report.conflicts += 1; - report.conflict_items.push(MergeConflict { - uuid: *uuid, - kind: ConflictKind::Group, - local_modified: left.times.last_modification.clone(), - remote_modified: right.times.last_modification.clone(), - fields: group_diff_fields(left, right), - }); + if group_content_key(left) == group_content_key(right) + && group_metadata_compatible(left, right) + { + // Same content; only optional metadata (notes, icon, + // auto-type flags) exists on one side, e.g. after a + // save by a build that dropped it. Keep the richer copy + // silently instead of asking about a non-edit. + let richer = if group_metadata_score(right) > group_metadata_score(left) { + right + } else { + left + }; + group = richer.clone(); + group.groups.clear(); + group.entries.clear(); + } else { + report.conflicts += 1; + report.conflict_items.push(MergeConflict { + uuid: *uuid, + kind: ConflictKind::Group, + local_modified: left.times.last_modification.clone(), + remote_modified: right.times.last_modification.clone(), + fields: group_diff_fields(left, right), + }); + } } } } @@ -172,8 +273,7 @@ pub fn merge(local: &Database, remote: &Database) -> (Database, MergeReport) { let mut merged_entries: BTreeMap = BTreeMap::new(); let mut entry_parent: BTreeMap = BTreeMap::new(); for uuid in &all_entry_uuids { - if deleted_uuids.contains(uuid) { - report.deleted_skipped += 1; + if entry_deleted.contains(uuid) { continue; } let (winner, loser) = match (a.entries.get(uuid), b.entries.get(uuid)) { @@ -188,6 +288,19 @@ pub fn merge(local: &Database, remote: &Database) -> (Database, MergeReport) { (right, left) } else if left_fp == right_fp { (left, right) + } else if entry_content_fingerprint(left) == entry_content_fingerprint(right) + && entry_metadata_compatible(left, right) + { + // Same content; only optional metadata (icon, colors, + // auto-type, custom data) exists on one side. This is what a + // save by an older build, or a client that omits those + // fields, looks like: keep the richer copy instead of asking + // about a change the user never made. + if entry_metadata_score(right) > entry_metadata_score(left) { + (right, left) + } else { + (left, right) + } } else { report.conflicts += 1; report.conflict_items.push(MergeConflict { @@ -239,35 +352,25 @@ pub fn merge(local: &Database, remote: &Database) -> (Database, MergeReport) { seen.push(candidate); } } + // KeePass keeps history oldest first; sorting before truncation + // makes the newest items the ones that survive the limits. + seen.sort_by_key(|snapshot| timestamp(&snapshot.times.last_modification)); let added = seen.len().saturating_sub(entry.history.len()); if !seen.is_empty() { entry.history = seen; } report.history_added += added; } + // The database that receives the merge owns the retention policy. + entry.truncate_history(limits); let local_parent = a.entry_parent.get(uuid).copied(); - let remote_parent = b.entry_parent.get(uuid).copied(); - let layout_side = if local_parent.is_some() && remote_parent.is_some() { - let left = a.entries.get(uuid).map(|entry| &entry.times); - let right = b.entries.get(uuid).map(|entry| &entry.times); - match (left, right) { - (Some(left), Some(right)) - if timestamp(&right.location_changed) > timestamp(&left.location_changed) => - { - remote_parent - } - _ => local_parent, - } - } else { - local_parent.or(remote_parent) - }; - let parent = layout_side.unwrap_or(root); - if deleted_groups.contains(&parent) { - report.deleted_skipped += 1; - continue; - } - let parent = if merged_groups.contains_key(&parent) { + // A surviving entry must not disappear just because its chosen parent + // group was deleted; move it to the root instead of dropping data. + let parent = choose_entry_parent(&a, &b, *uuid).unwrap_or(root); + let parent = if group_deleted.contains(&parent) { + root + } else if merged_groups.contains_key(&parent) { parent } else { root @@ -343,421 +446,14 @@ pub fn merge(local: &Database, remote: &Database) -> (Database, MergeReport) { (result, report) } -struct Side { - root: Uuid, - groups: BTreeMap, - group_parent: BTreeMap>, - entries: BTreeMap, - entry_parent: BTreeMap, - group_order: BTreeMap>, - entry_order: BTreeMap>, -} - -fn index(db: &Database) -> Side { - let mut side = Side { - root: db.root.uuid, - groups: BTreeMap::new(), - group_parent: BTreeMap::new(), - entries: BTreeMap::new(), - entry_parent: BTreeMap::new(), - group_order: BTreeMap::new(), - entry_order: BTreeMap::new(), - }; - walk(&db.root, None, &mut side); - side -} - -fn walk(group: &Group, parent: Option, side: &mut Side) { - let uuid = group.uuid; - let mut clean = group.clone(); - clean.groups.clear(); - clean.entries.clear(); - side.groups.insert(uuid, clean); - side.group_parent.insert(uuid, parent); - if let Some(parent) = parent { - side.group_order.entry(parent).or_default().push(uuid); - } - for entry in &group.entries { - side.entries.insert(entry.uuid, entry.clone()); - side.entry_parent.insert(entry.uuid, uuid); - side.entry_order.entry(uuid).or_default().push(entry.uuid); - } - for child in &group.groups { - walk(child, Some(uuid), side); - } -} - -fn build_group( - uuid: Uuid, - groups: &BTreeMap, - group_order: &BTreeMap>, - entry_order: &BTreeMap>, - entries: &BTreeMap, - visited: &mut BTreeSet, -) -> Group { - if !visited.insert(uuid) { - let mut group = groups.get(&uuid).cloned().unwrap_or_default(); - group.groups.clear(); - group.entries.clear(); - return group; - } - let mut group = groups.get(&uuid).cloned().unwrap_or_default(); - group.uuid = uuid; - group.groups = group_order - .get(&uuid) - .into_iter() - .flatten() - .map(|child| build_group(*child, groups, group_order, entry_order, entries, visited)) - .collect(); - group.entries = entry_order - .get(&uuid) - .into_iter() - .flatten() - .filter_map(|entry| entries.get(entry).cloned()) - .collect(); - group -} - -fn merge_deleted(local: &Database, remote: &Database) -> Vec { - let mut deleted = local.deleted_objects.clone(); - for item in &remote.deleted_objects { - if !deleted.iter().any(|existing| existing.uuid == item.uuid) { - deleted.push(item.clone()); - } - } - deleted -} - -fn parent_of_group(a: &Side, b: &Side, uuid: Uuid) -> Option { - a.group_parent - .get(&uuid) - .copied() - .flatten() - .or_else(|| b.group_parent.get(&uuid).copied().flatten()) -} - -fn choose_group<'a>(left: &'a Group, right: &'a Group) -> (&'a Group, Option<&'a Group>, bool) { - let left_time = timestamp(&left.times.last_modification); - let right_time = timestamp(&right.times.last_modification); - if left_time >= right_time { - (left, Some(right), true) - } else { - (right, Some(left), true) - } -} - -fn choose_parent( - a: &Side, - b: &Side, - parent_from: impl Fn(&Side) -> Option, - times_from: impl Fn(&Side) -> Option<&Times>, - root: Uuid, -) -> Uuid { - let left = parent_from(a); - let right = parent_from(b); - match (left, right) { - (Some(left), Some(right)) => { - let left_time = times_from(a) - .map(|times| timestamp(×.location_changed)) - .unwrap_or(0); - let right_time = times_from(b) - .map(|times| timestamp(×.location_changed)) - .unwrap_or(0); - if right_time > left_time { - right - } else { - left - } - } - (Some(left), None) => left, - (None, Some(right)) => right, - (None, None) => root, - } -} - -fn timestamp(value: &str) -> i64 { - crate::model::xml_datetime_to_unix(value).unwrap_or(i64::MIN) -} - -fn fingerprint(entry: &Entry) -> String { - let mut clean = entry.clone(); - clean.history.clear(); - clean.times = Times::default(); - clean.previous_parent_group = None; - serde_json::to_string(&clean).unwrap_or_default() -} - -fn group_fingerprint(group: &Group) -> String { - let mut clean = group.clone(); - clean.groups.clear(); - clean.entries.clear(); - clean.times = Times::default(); - clean.previous_parent_group = None; - serde_json::to_string(&clean).unwrap_or_default() -} - -fn entry_diff_fields(left: &Entry, right: &Entry) -> Vec { - let mut fields = BTreeSet::new(); - let mut keys = BTreeSet::new(); - keys.extend(left.strings.iter().map(|field| field.key.clone())); - keys.extend(right.strings.iter().map(|field| field.key.clone())); - for key in keys { - let left_value = left.strings.iter().find(|field| field.key == key); - let right_value = right.strings.iter().find(|field| field.key == key); - if left_value.map(|field| &field.value) != right_value.map(|field| &field.value) - || left_value.map(|field| field.protected) != right_value.map(|field| field.protected) - { - fields.insert(key); - } - } - if left.tags != right.tags { - fields.insert("Tags".to_string()); - } - if left.auto_type != right.auto_type { - fields.insert("AutoType".to_string()); - } - if left.binaries != right.binaries { - fields.insert("Attachments".to_string()); - } - if fields.is_empty() { - fields.insert("".to_string()); - } - fields.into_iter().collect() -} - -fn group_diff_fields(left: &Group, right: &Group) -> Vec { - let mut fields = Vec::new(); - if left.name != right.name { - fields.push("Name".to_string()); - } - if left.notes != right.notes { - fields.push("Notes".to_string()); - } - if left.tags != right.tags { - fields.push("Tags".to_string()); - } - if left.icon_id != right.icon_id { - fields.push("Icon".to_string()); - } - if fields.is_empty() { - fields.push("".to_string()); - } - fields -} - -fn snapshot_eq(left: &Entry, right: &Entry) -> bool { - fingerprint(left) == fingerprint(right) -} - +mod choice; +mod deletion; +mod index; #[cfg(test)] -mod tests { - use super::*; - use crate::model::{DeletedObject, Entry, StringField, Times}; - - fn uuid(byte: u8) -> Uuid { - Uuid::from_bytes([byte; 16]) - } - - fn time(second: u8) -> String { - format!("2026-10-25T10:00:{second:02}Z") - } - - fn entry(byte: u8, title: &str, modified: u8, location: u8) -> Entry { - let mut entry = Entry { - uuid: uuid(byte), - icon_id: 1, - tags: vec!["tag".to_string()], - times: Times { - creation: time(1), - last_modification: time(modified), - last_access: time(modified), - location_changed: time(location), - ..Times::default() - }, - ..Entry::default() - }; - entry.strings.push(StringField { - key: "Title".to_string(), - value: title.to_string(), - protected: false, - unknown: Vec::new(), - }); - entry - } - - fn database(entries: Vec) -> Database { - Database { - format_version: "4.0".to_string(), - root: Group { - uuid: uuid(1), - name: "Root".to_string(), - entries, - ..Group::default() - }, - ..Database::default() - } - } - - #[test] - fn same_database_is_idempotent() { - let a = database(vec![entry(2, "one", 2, 2)]); - let (result, report) = merge(&a, &a); - assert_eq!(result, a); - assert_eq!(report.conflicts, 0); - assert_eq!(report.entries_added, 0); - } - - #[test] - fn newer_entry_wins_and_loser_goes_to_history() { - let local = database(vec![entry(2, "old", 2, 2)]); - let remote = database(vec![entry(2, "new", 3, 2)]); - let (result, report) = merge(&local, &remote); - let merged = &result.root.entries[0]; - assert_eq!(merged.field("Title"), Some("new")); - assert_eq!(report.entries_updated, 1); - assert_eq!(merged.history.len(), 1); - assert_eq!(merged.history[0].field("Title"), Some("old")); - } - - #[test] - fn deleted_objects_prevent_resurrection() { - let mut remote = database(vec![entry(2, "deleted", 3, 3)]); - remote.deleted_objects = vec![DeletedObject { - uuid: uuid(2), - deletion_time: time(3), - }]; - let local = database(vec![entry(2, "old", 1, 1)]); - let (result, report) = merge(&local, &remote); - assert!(result.root.entries.is_empty()); - assert_eq!(result.deleted_objects.len(), 1); - assert!(report.deleted_skipped >= 1); - } - - #[test] - fn newer_location_changed_decides_parent() { - let entry_uuid = uuid(2); - let mut local = database(vec![]); - local.root.groups.push(Group { - uuid: uuid(3), - name: "A".to_string(), - entries: vec![entry(2, "x", 2, 2)], - ..Group::default() - }); - let mut remote = database(vec![]); - remote.root.groups.push(Group { - uuid: uuid(4), - name: "B".to_string(), - entries: vec![entry(2, "x", 2, 5)], - ..Group::default() - }); - assert_eq!(entry_uuid, local.root.groups[0].entries[0].uuid); - let (result, report) = merge(&local, &remote); - let group_b = result - .root - .groups - .iter() - .find(|group| group.uuid == uuid(4)) - .expect("B"); - assert!(group_b.entries.iter().any(|entry| entry.uuid == entry_uuid)); - let group_a = result - .root - .groups - .iter() - .find(|group| group.uuid == uuid(3)) - .expect("A"); - assert!(group_a.entries.is_empty()); - assert_eq!(report.moved, 1); - } - - #[test] - fn conflict_same_mtime_keeps_both_in_history() { - let local = database(vec![entry(2, "left", 3, 2)]); - let remote = database(vec![entry(2, "right", 3, 2)]); - let (result, report) = merge(&local, &remote); - assert_eq!(report.conflicts, 1); - let merged = &result.root.entries[0]; - assert_eq!(merged.history.len(), 1); - } - - #[test] - fn union_of_different_entries() { - let local = database(vec![entry(2, "two", 2, 2)]); - let remote = database(vec![entry(3, "three", 2, 2)]); - let (result, report) = merge(&local, &remote); - assert_eq!(result.root.entries.len(), 2); - assert_eq!(report.entries_added, 2); - } - - #[test] - fn merge_converges_without_duplicate_history() { - let local = database(vec![entry(2, "old", 2, 2)]); - let remote = database(vec![entry(2, "new", 3, 2)]); - let (first, _) = merge(&local, &remote); - let (second, report) = merge(&first, &remote); - assert_eq!(first, second); - assert_eq!(report.history_added, 0); - assert_eq!(second.root.entries[0].history.len(), 1); - } +mod tests; - #[test] - fn commutativity_preserves_entries_and_parents() { - let mut local = database(vec![entry(2, "shared", 2, 2)]); - local.root.groups.push(Group { - uuid: uuid(3), - name: "A".to_string(), - ..Group::default() - }); - let mut remote = database(vec![entry(4, "remote-only", 2, 2)]); - remote.root.groups.push(Group { - uuid: uuid(5), - name: "B".to_string(), - ..Group::default() - }); - let layout = |db: &Database| { - let mut out = BTreeMap::new(); - fn walk(group: &Group, parent: Option, out: &mut BTreeMap>) { - out.insert(group.uuid, parent); - for entry in &group.entries { - out.insert(entry.uuid, Some(group.uuid)); - } - for child in &group.groups { - walk(child, Some(group.uuid), out); - } - } - walk(&db.root, None, &mut out); - out - }; - let (left, _) = merge(&local, &remote); - let (right, _) = merge(&remote, &local); - assert_eq!(layout(&left), layout(&right)); - } - - #[test] - fn deleted_group_subtree_is_removed() { - let mut local = database(vec![]); - local.root.groups.push(Group { - uuid: uuid(3), - name: "Doomed".to_string(), - entries: vec![entry(2, "child", 2, 2)], - ..Group::default() - }); - let mut remote = database(vec![entry(9, "live", 2, 2)]); - remote.deleted_objects.push(DeletedObject { - uuid: uuid(3), - deletion_time: time(3), - }); - let (result, report) = merge(&local, &remote); - assert!(!result.root.groups.iter().any(|group| group.uuid == uuid(3))); - assert!(!result - .root - .entries - .iter() - .any(|entry| entry.uuid == uuid(2))); - assert!(result - .root - .entries - .iter() - .any(|entry| entry.uuid == uuid(9))); - assert!(report.deleted_skipped >= 2); - } -} +// The helpers are private to the merge algorithm; they are re-exported here so +// the merge entry point calls them by their bare names, as the single file did. +use choice::*; +use deletion::*; +use index::*; diff --git a/crates/core/src/merge/tests.rs b/crates/core/src/merge/tests.rs new file mode 100644 index 0000000..be089cb --- /dev/null +++ b/crates/core/src/merge/tests.rs @@ -0,0 +1,211 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +use super::*; +use crate::model::{DeletedObject, Entry, StringField, Times}; + +fn uuid(byte: u8) -> Uuid { + Uuid::from_bytes([byte; 16]) +} + +fn time(second: u8) -> String { + format!("2026-10-25T10:00:{second:02}Z") +} + +fn entry(byte: u8, title: &str, modified: u8, location: u8) -> Entry { + let mut entry = Entry { + uuid: uuid(byte), + icon_id: 1, + tags: vec!["tag".to_string()], + times: Times { + creation: time(1), + last_modification: time(modified), + last_access: time(modified), + location_changed: time(location), + ..Times::default() + }, + ..Entry::default() + }; + entry.strings.push(StringField { + key: "Title".to_string(), + value: title.to_string(), + protected: false, + unknown: Vec::new(), + }); + entry +} + +fn database(entries: Vec) -> Database { + Database { + format_version: "4.0".to_string(), + root: Group { + uuid: uuid(1), + name: "Root".to_string(), + entries, + ..Group::default() + }, + ..Database::default() + } +} + +#[test] +fn same_database_is_idempotent() { + let a = database(vec![entry(2, "one", 2, 2)]); + let (result, report) = merge(&a, &a); + assert_eq!(result, a); + assert_eq!(report.conflicts, 0); + assert_eq!(report.entries_added, 0); +} + +#[test] +fn newer_entry_wins_and_loser_goes_to_history() { + let local = database(vec![entry(2, "old", 2, 2)]); + let remote = database(vec![entry(2, "new", 3, 2)]); + let (result, report) = merge(&local, &remote); + let merged = &result.root.entries[0]; + assert_eq!(merged.field("Title"), Some("new")); + assert_eq!(report.entries_updated, 1); + assert_eq!(merged.history.len(), 1); + assert_eq!(merged.history[0].field("Title"), Some("old")); +} + +#[test] +fn deleted_objects_prevent_resurrection() { + let mut remote = database(vec![entry(2, "deleted", 3, 3)]); + remote.deleted_objects = vec![DeletedObject { + uuid: uuid(2), + deletion_time: time(3), + }]; + let local = database(vec![entry(2, "old", 1, 1)]); + let (result, report) = merge(&local, &remote); + assert!(result.root.entries.is_empty()); + assert_eq!(result.deleted_objects.len(), 1); + assert!(report.deleted_skipped >= 1); +} + +#[test] +fn newer_location_changed_decides_parent() { + let entry_uuid = uuid(2); + let mut local = database(vec![]); + local.root.groups.push(Group { + uuid: uuid(3), + name: "A".to_string(), + entries: vec![entry(2, "x", 2, 2)], + ..Group::default() + }); + let mut remote = database(vec![]); + remote.root.groups.push(Group { + uuid: uuid(4), + name: "B".to_string(), + entries: vec![entry(2, "x", 2, 5)], + ..Group::default() + }); + assert_eq!(entry_uuid, local.root.groups[0].entries[0].uuid); + let (result, report) = merge(&local, &remote); + let group_b = result + .root + .groups + .iter() + .find(|group| group.uuid == uuid(4)) + .expect("B"); + assert!(group_b.entries.iter().any(|entry| entry.uuid == entry_uuid)); + let group_a = result + .root + .groups + .iter() + .find(|group| group.uuid == uuid(3)) + .expect("A"); + assert!(group_a.entries.is_empty()); + assert_eq!(report.moved, 1); +} + +#[test] +fn conflict_same_mtime_keeps_both_in_history() { + let local = database(vec![entry(2, "left", 3, 2)]); + let remote = database(vec![entry(2, "right", 3, 2)]); + let (result, report) = merge(&local, &remote); + assert_eq!(report.conflicts, 1); + let merged = &result.root.entries[0]; + assert_eq!(merged.history.len(), 1); +} + +#[test] +fn union_of_different_entries() { + let local = database(vec![entry(2, "two", 2, 2)]); + let remote = database(vec![entry(3, "three", 2, 2)]); + let (result, report) = merge(&local, &remote); + assert_eq!(result.root.entries.len(), 2); + assert_eq!(report.entries_added, 2); +} + +#[test] +fn merge_converges_without_duplicate_history() { + let local = database(vec![entry(2, "old", 2, 2)]); + let remote = database(vec![entry(2, "new", 3, 2)]); + let (first, _) = merge(&local, &remote); + let (second, report) = merge(&first, &remote); + assert_eq!(first, second); + assert_eq!(report.history_added, 0); + assert_eq!(second.root.entries[0].history.len(), 1); +} + +#[test] +fn commutativity_preserves_entries_and_parents() { + let mut local = database(vec![entry(2, "shared", 2, 2)]); + local.root.groups.push(Group { + uuid: uuid(3), + name: "A".to_string(), + ..Group::default() + }); + let mut remote = database(vec![entry(4, "remote-only", 2, 2)]); + remote.root.groups.push(Group { + uuid: uuid(5), + name: "B".to_string(), + ..Group::default() + }); + let layout = |db: &Database| { + let mut out = BTreeMap::new(); + fn walk(group: &Group, parent: Option, out: &mut BTreeMap>) { + out.insert(group.uuid, parent); + for entry in &group.entries { + out.insert(entry.uuid, Some(group.uuid)); + } + for child in &group.groups { + walk(child, Some(group.uuid), out); + } + } + walk(&db.root, None, &mut out); + out + }; + let (left, _) = merge(&local, &remote); + let (right, _) = merge(&remote, &local); + assert_eq!(layout(&left), layout(&right)); +} + +#[test] +fn deleted_group_subtree_is_removed() { + let mut local = database(vec![]); + local.root.groups.push(Group { + uuid: uuid(3), + name: "Doomed".to_string(), + entries: vec![entry(2, "child", 2, 2)], + ..Group::default() + }); + let mut remote = database(vec![entry(9, "live", 2, 2)]); + remote.deleted_objects.push(DeletedObject { + uuid: uuid(3), + deletion_time: time(3), + }); + let (result, report) = merge(&local, &remote); + assert!(!result.root.groups.iter().any(|group| group.uuid == uuid(3))); + assert!(!result + .root + .entries + .iter() + .any(|entry| entry.uuid == uuid(2))); + assert!(result + .root + .entries + .iter() + .any(|entry| entry.uuid == uuid(9))); + assert!(report.deleted_skipped >= 2); +} diff --git a/crates/core/src/model/database.rs b/crates/core/src/model/database.rs new file mode 100644 index 0000000..f53d48e --- /dev/null +++ b/crates/core/src/model/database.rs @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! The database root, its redaction helper and secret-key filtering. + +use super::*; + +impl Database { + /// Replace the KDF the next save writes. + /// + /// This is the only way this app changes a database's parameters: an + /// explicit, user-initiated edit. Saving never picks different parameters on + /// its own, and a rejected value leaves the model untouched. + pub fn set_kdf(&mut self, kdf: KdfSettings) -> Result<(), KdfError> { + kdf.validate()?; + let outer = self.outer.get_or_insert_with(OuterHeader::for_new_database); + outer.kdf = Some(kdf); + Ok(()) + } +} + +/// Whole database model (everything decrypted). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Database { + /// Format version as detected by [`crate::kdbx`] (`"3.1"` / `"4.0"` / `"4.1"`). + pub format_version: String, + /// KDBX4 outer header settings. Not serialized: it is file metadata, not + /// vault content, and the writer needs the source values to preserve them. + #[serde(skip)] + pub outer: Option, + /// ``. + pub meta: Meta, + /// Root group. + pub root: Group, + /// Deleted-object records. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub deleted_objects: Vec, + /// Unknown database-level XML. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub unknown: Vec, + /// Raw decrypted XML bytes (not serialized; may contain secrets). + /// + /// Kept so M1-02 does not lose data that the reader model does not map yet; + /// canonical dumps expose only its SHA-256, never the bytes. + #[serde(skip)] + pub raw_xml: Option>, + /// SHA-256 of [`Database::raw_xml`], included in canonical dumps as + /// evidence that unknown XML was preserved without leaking secrets. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub raw_xml_sha256: Option, +} + +impl Database { + /// Canonical JSON dump of the full model. + /// + /// Keys are emitted in struct order; deterministic collections use + /// `BTreeMap`/sorted keys. Structural order (groups/entries/strings) is kept + /// because it is meaningful for KeePass display and round-trip fidelity. + /// + /// Secret values (protected strings, `Password`, TOTP seeds) are replaced by + /// `sha256:` so a dump can be compared/logged without leaking them. + pub fn canonical_json(&self) -> Result { + let mut value = serde_json::to_value(self)?; + redact_value(&mut value); + serde_json::to_string_pretty(&value) + } + + /// Canonical JSON value (useful for tests/tools); secrets are redacted. + pub fn canonical_value(&self) -> Result { + let mut value = serde_json::to_value(self)?; + redact_value(&mut value); + Ok(value) + } +} + +pub(crate) fn is_secret_key(key: &str) -> bool { + key == "Password" + || key == "otp" + || key == "TOTP Seed" + || key.starts_with("TimeOtp-Secret") + || key.ends_with("_secret") +} + +pub(crate) fn redact_value(value: &mut serde_json::Value) { + match value { + serde_json::Value::Array(items) => { + for item in items { + redact_value(item); + } + } + serde_json::Value::Object(map) => { + let secret = map + .get("key") + .and_then(|key| key.as_str()) + .is_some_and(is_secret_key) + || map + .get("protected") + .and_then(|flag| flag.as_bool()) + .unwrap_or(false); + if secret { + if let Some(serde_json::Value::String(text)) = map.get_mut("value") { + let digest = sha2::Sha256::digest(text.as_bytes()); + let mut hex = String::with_capacity(digest.len() * 2); + for byte in digest { + hex.push_str(&format!("{byte:02x}")); + } + *text = format!("sha256:{hex}"); + } + if let Some(serde_json::Value::String(text)) = map.get_mut("password_secret") { + let digest = sha2::Sha256::digest(text.as_bytes()); + let mut hex = String::with_capacity(digest.len() * 2); + for byte in digest { + hex.push_str(&format!("{byte:02x}")); + } + *text = format!("sha256:{hex}"); + } + } + for child in map.values_mut() { + redact_value(child); + } + } + _ => {} + } +} diff --git a/crates/core/src/model/entry.rs b/crates/core/src/model/entry.rs new file mode 100644 index 0000000..95bb593 --- /dev/null +++ b/crates/core/src/model/entry.rs @@ -0,0 +1,187 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Entries: fields, binaries, associations and auto-type. + +use super::*; + +/// One `` entry of an entry. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct StringField { + /// Field key (`Title`, `UserName`, `Password`, `URL`, `Notes`, custom keys). + pub key: String, + /// Plain value (only in memory, inside the encrypted container). + pub value: String, + /// `Protected="True"` flag. + pub protected: bool, + /// Unknown children/attributes. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub unknown: Vec, +} + +/// One `` reference on an entry (actual bytes in the inner header). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Binary { + /// Attachment key (file name). + pub key: String, + /// Attachment bytes (resolved from the inner header). + #[serde(with = "hex_bytes")] + pub value: Vec, + /// Protected flag (`Flags` in the inner header). + pub protected: bool, + /// Unknown children. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub unknown: Vec, +} + +/// Auto-type association. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Association { + /// Window title pattern. + pub window: String, + /// Keystroke sequence. + pub keystroke_sequence: String, + /// Unknown children. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub unknown: Vec, +} + +/// `` block. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct AutoType { + /// Enabled flag. + pub enabled: bool, + /// Data transfer obfuscation flag. + pub data_transfer_obfuscation: bool, + /// Default sequence. + pub default_sequence: String, + /// Associations. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub associations: Vec, + /// Unknown children. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub unknown: Vec, +} + +/// One `` (also used for history entries). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Entry { + /// UUID. + pub uuid: Uuid, + /// Numeric icon id. + pub icon_id: u32, + /// Custom icon UUID (KDBX 4.x); set when the entry uses one of the + /// database's custom icons instead of a built-in one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub custom_icon_uuid: Option, + /// Foreground color text (KDBX 4.1). + pub foreground_color: String, + /// Background color text (KDBX 4.1). + pub background_color: String, + /// Override-URL flag/string. + pub override_url: String, + /// Tags. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tags: Vec, + /// Previous parent group UUID (merge hint). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub previous_parent_group: Option, + /// Times. + pub times: Times, + /// String fields (`Title`/`UserName`/... and custom fields). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub strings: Vec, + /// Attachments. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub binaries: Vec, + /// Auto-type settings. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub auto_type: Option, + /// History entries, oldest first. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub history: Vec, + /// Custom data. + pub custom_data: CustomData, + /// Unknown children. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub unknown: Vec, +} + +impl Entry { + /// Standard field value (e.g. `Title`). + pub fn field(&self, key: &str) -> Option<&str> { + self.strings + .iter() + .find(|field| field.key == key) + .map(|field| field.value.as_str()) + } + + /// `true` when the entry has an `otp` or KeePass `TimeOtp-*` field. + pub fn has_totp(&self) -> bool { + self.strings.iter().any(|field| { + field.key == "otp" + || field.key.starts_with("TimeOtp-") + || field.key == "TOTP Seed" + || field.key == "TOTP Settings" + }) + } + + /// Approximate byte size used for ``. + /// + /// KeePass limits history by an approximate serialized size. Counting field + /// names and values, attachment names and bytes, and tags mirrors the + /// vendored keepassxcr `Entry::size` implementation closely enough for the + /// limit, without requiring a serializer here (core stays IO-free). + pub fn approximate_size(&self) -> i64 { + let fields: usize = self + .strings + .iter() + .map(|field| field.key.len() + field.value.len()) + .sum(); + let binaries: usize = self + .binaries + .iter() + .map(|binary| binary.key.len() + binary.value.len()) + .sum(); + let tags: usize = self.tags.iter().map(String::len).sum(); + i64::try_from(fields + binaries + tags).unwrap_or(i64::MAX) + } + + /// Drop the oldest history items beyond `limits`. + /// + /// This is the KeePass retention rule: a negative limit disables that + /// dimension, while zero keeps no history. The newest items survive. + pub fn truncate_history(&mut self, limits: HistoryLimits) { + if limits.max_items >= 0 { + let max_items = usize::try_from(limits.max_items).unwrap_or(usize::MAX); + if self.history.len() > max_items { + let excess = self.history.len() - max_items; + self.history.drain(..excess); + } + } + if limits.max_size >= 0 { + let mut total = 0i64; + let mut keep = 0usize; + for item in self.history.iter().rev() { + total = total.saturating_add(item.approximate_size()); + if total > limits.max_size { + break; + } + keep += 1; + } + let excess = self.history.len() - keep; + self.history.drain(..excess); + } + } + + /// Record the current state as the newest history item, then apply limits. + /// + /// Callers change the entry afterwards (and set the new modification time), + /// so the previous password and fields remain recoverable. The snapshot does + /// not nest history and does not keep a merge-only previous-parent hint. + pub fn push_history_snapshot(&mut self, limits: HistoryLimits) { + let mut snapshot = self.clone(); + snapshot.history.clear(); + snapshot.previous_parent_group = None; + self.history.push(snapshot); + self.truncate_history(limits); + } +} diff --git a/crates/core/src/model/group.rs b/crates/core/src/model/group.rs new file mode 100644 index 0000000..cf68b1f --- /dev/null +++ b/crates/core/src/model/group.rs @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Groups and deletion tombstones. + +use super::*; + +/// One `` (root group included). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Group { + /// UUID. + pub uuid: Uuid, + /// Name. + pub name: String, + /// Notes. + pub notes: String, + /// Numeric icon id. + pub icon_id: u32, + /// Custom icon UUID (KDBX 4.x); set when the group uses one of the + /// database's custom icons instead of a built-in one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub custom_icon_uuid: Option, + /// Times. + pub times: Times, + /// UI expand flag. + pub is_expanded: bool, + /// Default auto-type enabled. + pub default_auto_type: bool, + /// Default auto-type sequence for the group. + pub default_autotype_sequence: String, + /// Auto-type enabled. + pub enable_auto_type: bool, + /// Searching enabled. + pub enable_searching: bool, + /// Last visible top entry. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_top_visible_entry: Option, + /// Tags. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tags: Vec, + /// Previous parent group UUID. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub previous_parent_group: Option, + /// Custom data. + pub custom_data: CustomData, + /// Child groups (order preserved). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub groups: Vec, + /// Entries (order preserved). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub entries: Vec, + /// Unknown children. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub unknown: Vec, +} + +/// One ``. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct DeletedObject { + /// UUID of the deleted object. + pub uuid: Uuid, + /// Deletion time text. + pub deletion_time: String, +} diff --git a/crates/core/src/model/meta.rs b/crates/core/src/model/meta.rs new file mode 100644 index 0000000..12f48c7 --- /dev/null +++ b/crates/core/src/model/meta.rs @@ -0,0 +1,195 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Database metadata: memory protection, custom data, icons and history limits. + +use super::*; + +/// Memory-protection flags from KDBX ``. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct MemoryProtection { + /// Protect title field. + pub protect_title: bool, + /// Protect username field. + pub protect_username: bool, + /// Protect password field. + pub protect_password: bool, + /// Protect URL field. + pub protect_url: bool, + /// Protect notes field. + pub protect_notes: bool, + /// Unknown children. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub unknown: Vec, +} + +impl Default for MemoryProtection { + fn default() -> Self { + Self { + protect_title: false, + protect_username: false, + protect_password: true, + protect_url: false, + protect_notes: false, + unknown: Vec::new(), + } + } +} + +/// Value of a custom-data item. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum CustomDataValue { + /// Text value. + String(String), + /// Binary value (hex-encoded in JSON to keep dumps readable). + Binary(#[serde(with = "hex_bytes")] Vec), +} + +/// One `` inside ``. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct CustomDataItem { + /// Item value (absent means empty item). + #[serde(default)] + pub value: Option, + /// `LastModificationTime` text. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_modification: Option, + /// Unknown children. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub unknown: Vec, +} + +/// `` block (stable key order). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct CustomData { + /// Items keyed by plugin/name. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub items: BTreeMap, + /// Unknown children. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub unknown: Vec, +} + +/// One custom icon from ``. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct CustomIcon { + /// Icon UUID. + pub uuid: Uuid, + /// Raw image bytes. + #[serde(with = "hex_bytes")] + pub data: Vec, + /// Optional `Name` (KDBX 4.1). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + /// Optional `LastModificationTime` (KDBX 4.1). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_modification: Option, + /// Unknown children. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub unknown: Vec, +} + +/// History items kept per entry when the database does not say. KeePass and +/// KeePassXC both default to 10, so an omitted `` must not be +/// read as "keep nothing". +pub const DEFAULT_HISTORY_MAX_ITEMS: i64 = 10; +/// Total history size kept per entry when the database does not say (6 MiB, +/// the KeePass default). +pub const DEFAULT_HISTORY_MAX_SIZE: i64 = 6 * 1024 * 1024; + +/// `` block. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Meta { + /// Generator string. + pub generator: String, + /// Database name. + pub database_name: String, + /// Database description. + pub database_description: String, + /// Default username for new entries. + pub default_username: String, + /// Memory protection flags. + pub memory_protection: MemoryProtection, + /// Recycle-bin enabled flag. + pub recycle_bin_enabled: bool, + /// Recycle-bin group UUID. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub recycle_bin_uuid: Option, + /// Recycle-bin changed time. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub recycle_bin_changed: Option, + /// History max items setting. + pub history_max_items: i64, + /// History max size setting. + pub history_max_size: i64, + /// Custom data. + pub custom_data: CustomData, + /// Custom icons. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub custom_icons: Vec, + /// Unknown children (maintenance history, etc.). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub unknown: Vec, +} + +impl Default for Meta { + fn default() -> Self { + // Mirror the KDBX defaults: a new or partially specified database has + // the recycle bin and bounded history enabled, not everything disabled. + // `Meta::default()` is also the base of `Database::default()`, so tests + // and the empty-database writer rely on these values. + Self { + generator: String::new(), + database_name: String::new(), + database_description: String::new(), + default_username: String::new(), + memory_protection: MemoryProtection::default(), + recycle_bin_enabled: true, + recycle_bin_uuid: None, + recycle_bin_changed: None, + history_max_items: DEFAULT_HISTORY_MAX_ITEMS, + history_max_size: DEFAULT_HISTORY_MAX_SIZE, + custom_data: CustomData::default(), + custom_icons: Vec::new(), + unknown: Vec::new(), + } + } +} + +/// How much history an entry keeps, from ``. +/// +/// A negative value means no limit (KeePass semantics); zero means keep no +/// history at all. The reader fills omitted XML elements with the KeePass +/// defaults, so the values are used verbatim here. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct HistoryLimits { + /// Most history items per entry. + pub max_items: i64, + /// Most bytes of history per entry, counted by [`Entry::approximate_size`]. + pub max_size: i64, +} + +impl Default for HistoryLimits { + fn default() -> Self { + Self { + max_items: DEFAULT_HISTORY_MAX_ITEMS, + max_size: DEFAULT_HISTORY_MAX_SIZE, + } + } +} + +impl HistoryLimits { + /// Limits of a database `` block. + pub fn from_meta(meta: &Meta) -> Self { + Self { + max_items: meta.history_max_items, + max_size: meta.history_max_size, + } + } + + /// No limits (all history kept). + pub fn unlimited() -> Self { + Self { + max_items: -1, + max_size: -1, + } + } +} diff --git a/crates/core/src/model/mod.rs b/crates/core/src/model/mod.rs index 48148fc..691507d 100644 --- a/crates/core/src/model/mod.rs +++ b/crates/core/src/model/mod.rs @@ -12,618 +12,6 @@ use std::collections::BTreeMap; use std::fmt; use std::str::FromStr; -/// 16-byte UUID as used by KDBX. Serialized as 32 lowercase hex characters. -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] -pub struct Uuid([u8; 16]); - -impl Uuid { - /// Create from raw bytes. - pub fn from_bytes(bytes: [u8; 16]) -> Self { - Self(bytes) - } - - /// All-zero UUID (KDBX "no value"). - pub fn nil() -> Self { - Self([0u8; 16]) - } - - /// Raw bytes. - pub fn as_bytes(&self) -> &[u8; 16] { - &self.0 - } - - /// `true` for the all-zero UUID. - pub fn is_nil(&self) -> bool { - self.0 == [0u8; 16] - } - - /// 32 lowercase hex characters. - pub fn to_hex(self) -> String { - let mut out = String::with_capacity(32); - for byte in self.0 { - out.push_str(&format!("{byte:02x}")); - } - out - } -} - -impl fmt::Display for Uuid { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.to_hex()) - } -} - -impl fmt::Debug for Uuid { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "Uuid({})", self.to_hex()) - } -} - -impl FromStr for Uuid { - type Err = String; - - fn from_str(value: &str) -> Result { - let value = value.trim(); - let hex = value.replace('-', ""); - if hex.len() != 32 { - return Err(format!("invalid UUID length: {}", hex.len())); - } - let mut bytes = [0u8; 16]; - for (index, byte) in bytes.iter_mut().enumerate() { - let start = index * 2; - *byte = u8::from_str_radix(&hex[start..start + 2], 16) - .map_err(|_| format!("invalid UUID hex: {value}"))?; - } - Ok(Self(bytes)) - } -} - -impl Serialize for Uuid { - fn serialize(&self, serializer: S) -> Result { - serializer.serialize_str(&self.to_hex()) - } -} - -impl<'de> Deserialize<'de> for Uuid { - fn deserialize>(deserializer: D) -> Result { - let value = String::deserialize(deserializer)?; - value.parse().map_err(serde::de::Error::custom) - } -} - -/// Raw XML element preserved verbatim for unknown tags/attributes. -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct RawXml { - /// Element name (e.g. `CustomPluginData`). - pub name: String, - /// Attributes in deterministic order. - #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] - pub attributes: BTreeMap, - /// Direct text content, if any. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub text: Option, - /// Nested elements. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub children: Vec, -} - -impl RawXml { - /// Empty element with a name. - pub fn new(name: impl Into) -> Self { - Self { - name: name.into(), - ..Self::default() - } - } -} - -/// KDBX times block. Strings keep the original XML date-time text so a rewrite -/// is byte-faithful; helpers convert to Unix seconds for DTOs. -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct Times { - /// `CreationTime`. - pub creation: String, - /// `LastModificationTime` — determines newness in merge. - pub last_modification: String, - /// `LastAccessTime`. - pub last_access: String, - /// `ExpiryTime` (only meaningful when `expires`). - pub expiry: String, - /// `Expires` flag. - pub expires: bool, - /// `UsageCount`. - pub usage_count: u64, - /// `LocationChanged` — determines latest location after a move. - pub location_changed: String, - /// Unknown child elements. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub unknown: Vec, -} - -impl Times { - /// Parsed `CreationTime` as Unix seconds. - pub fn created_unix(&self) -> Option { - xml_datetime_to_unix(&self.creation) - } - - /// Parsed `LastModificationTime` as Unix seconds. - pub fn modified_unix(&self) -> Option { - xml_datetime_to_unix(&self.last_modification) - } - - /// Parsed `LastAccessTime` as Unix seconds. - pub fn accessed_unix(&self) -> Option { - xml_datetime_to_unix(&self.last_access) - } - - /// Parsed `ExpiryTime` as Unix seconds when `expires` is set. - pub fn expires_unix(&self) -> Option { - if self.expires { - xml_datetime_to_unix(&self.expiry) - } else { - None - } - } -} - -/// Parse the KDBX UTC date-time format (`YYYY-MM-DDTHH:MM:SS[.fraction]Z`). -/// -/// Returns `None` for formats this minimal parser does not understand; callers -/// keep the raw string in that case. -pub fn xml_datetime_to_unix(value: &str) -> Option { - let bytes = value.as_bytes(); - if bytes.len() < 20 || bytes[4] != b'-' || bytes[7] != b'-' || bytes[10] != b'T' { - return None; - } - if bytes[13] != b':' || bytes[16] != b':' { - return None; - } - let year = value.get(0..4)?.parse::().ok()?; - let month = value.get(5..7)?.parse::().ok()?; - let day = value.get(8..10)?.parse::().ok()?; - let hour = value.get(11..13)?.parse::().ok()?; - let minute = value.get(14..16)?.parse::().ok()?; - let second = value.get(17..19)?.parse::().ok()?; - if !value.ends_with('Z') { - return None; - } - if !(1..=12).contains(&month) || !(1..=31).contains(&day) { - return None; - } - let days = days_from_civil(year, month, day); - Some(days * 86_400 + hour * 3_600 + minute * 60 + second) -} - -fn days_from_civil(year: i64, month: u32, day: u32) -> i64 { - let year = year - i64::from(month <= 2); - let era = if year >= 0 { year } else { year - 399 } / 400; - let year_of_era = year - era * 400; - let month = month as i64; - let day_of_year = (153 * (month + if month > 2 { -3 } else { 9 }) + 2) / 5 + day as i64 - 1; - let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; - era * 146_097 + day_of_era - 719_468 -} - -/// Format Unix seconds as the KDBX UTC date-time string -/// (`YYYY-MM-DDTHH:MM:SSZ`). -/// -/// The platform layer supplies the clock; this function is pure. -pub fn xml_datetime_from_unix(seconds: i64) -> String { - let days = seconds.div_euclid(86_400); - let second_of_day = seconds.rem_euclid(86_400); - let (year, month, day) = civil_from_days(days); - let hour = second_of_day / 3_600; - let minute = (second_of_day % 3_600) / 60; - let second = second_of_day % 60; - format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z") -} - -fn civil_from_days(days: i64) -> (i64, u32, u32) { - let z = days + 719_468; - let era = if z >= 0 { z } else { z - 146_096 } / 146_097; - let day_of_era = z - era * 146_097; - let year_of_era = - (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; - let year = year_of_era + era * 400; - let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); - let month_prime = (5 * day_of_year + 2) / 153; - let day = day_of_year - (153 * month_prime + 2) / 5 + 1; - let month = month_prime + if month_prime < 10 { 3 } else { -9 }; - let year = year + i64::from(month <= 2); - (year, month as u32, day as u32) -} - -/// Memory-protection flags from KDBX ``. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct MemoryProtection { - /// Protect title field. - pub protect_title: bool, - /// Protect username field. - pub protect_username: bool, - /// Protect password field. - pub protect_password: bool, - /// Protect URL field. - pub protect_url: bool, - /// Protect notes field. - pub protect_notes: bool, - /// Unknown children. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub unknown: Vec, -} - -impl Default for MemoryProtection { - fn default() -> Self { - Self { - protect_title: false, - protect_username: false, - protect_password: true, - protect_url: false, - protect_notes: false, - unknown: Vec::new(), - } - } -} - -/// Value of a custom-data item. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum CustomDataValue { - /// Text value. - String(String), - /// Binary value (hex-encoded in JSON to keep dumps readable). - Binary(#[serde(with = "hex_bytes")] Vec), -} - -/// One `` inside ``. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct CustomDataItem { - /// Item value (absent means empty item). - #[serde(default)] - pub value: Option, - /// `LastModificationTime` text. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub last_modification: Option, - /// Unknown children. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub unknown: Vec, -} - -/// `` block (stable key order). -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct CustomData { - /// Items keyed by plugin/name. - #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] - pub items: BTreeMap, - /// Unknown children. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub unknown: Vec, -} - -/// One custom icon from ``. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct CustomIcon { - /// Icon UUID. - pub uuid: Uuid, - /// Raw image bytes. - #[serde(with = "hex_bytes")] - pub data: Vec, - /// Optional `Name` (KDBX 4.1). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub name: Option, - /// Optional `LastModificationTime` (KDBX 4.1). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub last_modification: Option, - /// Unknown children. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub unknown: Vec, -} - -/// `` block. -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct Meta { - /// Generator string. - pub generator: String, - /// Database name. - pub database_name: String, - /// Database description. - pub database_description: String, - /// Default username for new entries. - pub default_username: String, - /// Memory protection flags. - pub memory_protection: MemoryProtection, - /// Recycle-bin enabled flag. - pub recycle_bin_enabled: bool, - /// Recycle-bin group UUID. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub recycle_bin_uuid: Option, - /// Recycle-bin changed time. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub recycle_bin_changed: Option, - /// History max items setting. - pub history_max_items: i64, - /// History max size setting. - pub history_max_size: i64, - /// Custom data. - pub custom_data: CustomData, - /// Custom icons. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub custom_icons: Vec, - /// Unknown children (maintenance history, etc.). - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub unknown: Vec, -} - -/// One `` entry of an entry. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct StringField { - /// Field key (`Title`, `UserName`, `Password`, `URL`, `Notes`, custom keys). - pub key: String, - /// Plain value (only in memory, inside the encrypted container). - pub value: String, - /// `Protected="True"` flag. - pub protected: bool, - /// Unknown children/attributes. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub unknown: Vec, -} - -/// One `` reference on an entry (actual bytes in the inner header). -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct Binary { - /// Attachment key (file name). - pub key: String, - /// Attachment bytes (resolved from the inner header). - #[serde(with = "hex_bytes")] - pub value: Vec, - /// Protected flag (`Flags` in the inner header). - pub protected: bool, - /// Unknown children. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub unknown: Vec, -} - -/// Auto-type association. -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct Association { - /// Window title pattern. - pub window: String, - /// Keystroke sequence. - pub keystroke_sequence: String, - /// Unknown children. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub unknown: Vec, -} - -/// `` block. -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct AutoType { - /// Enabled flag. - pub enabled: bool, - /// Data transfer obfuscation flag. - pub data_transfer_obfuscation: bool, - /// Default sequence. - pub default_sequence: String, - /// Associations. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub associations: Vec, - /// Unknown children. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub unknown: Vec, -} - -/// One `` (also used for history entries). -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct Entry { - /// UUID. - pub uuid: Uuid, - /// Numeric icon id. - pub icon_id: u32, - /// Foreground color text (KDBX 4.1). - pub foreground_color: String, - /// Background color text (KDBX 4.1). - pub background_color: String, - /// Override-URL flag/string. - pub override_url: String, - /// Tags. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub tags: Vec, - /// Previous parent group UUID (merge hint). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub previous_parent_group: Option, - /// Times. - pub times: Times, - /// String fields (`Title`/`UserName`/... and custom fields). - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub strings: Vec, - /// Attachments. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub binaries: Vec, - /// Auto-type settings. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub auto_type: Option, - /// History entries, oldest first. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub history: Vec, - /// Custom data. - pub custom_data: CustomData, - /// Unknown children. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub unknown: Vec, -} - -impl Entry { - /// Standard field value (e.g. `Title`). - pub fn field(&self, key: &str) -> Option<&str> { - self.strings - .iter() - .find(|field| field.key == key) - .map(|field| field.value.as_str()) - } - - /// `true` when the entry has an `otp` or KeePass `TimeOtp-*` field. - pub fn has_totp(&self) -> bool { - self.strings.iter().any(|field| { - field.key == "otp" - || field.key.starts_with("TimeOtp-") - || field.key == "TOTP Seed" - || field.key == "TOTP Settings" - }) - } -} - -/// One `` (root group included). -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct Group { - /// UUID. - pub uuid: Uuid, - /// Name. - pub name: String, - /// Notes. - pub notes: String, - /// Numeric icon id. - pub icon_id: u32, - /// Times. - pub times: Times, - /// UI expand flag. - pub is_expanded: bool, - /// Default auto-type enabled. - pub default_auto_type: bool, - /// Default auto-type sequence for the group. - pub default_autotype_sequence: String, - /// Auto-type enabled. - pub enable_auto_type: bool, - /// Searching enabled. - pub enable_searching: bool, - /// Last visible top entry. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub last_top_visible_entry: Option, - /// Tags. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub tags: Vec, - /// Previous parent group UUID. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub previous_parent_group: Option, - /// Custom data. - pub custom_data: CustomData, - /// Child groups (order preserved). - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub groups: Vec, - /// Entries (order preserved). - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub entries: Vec, - /// Unknown children. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub unknown: Vec, -} - -/// One ``. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct DeletedObject { - /// UUID of the deleted object. - pub uuid: Uuid, - /// Deletion time text. - pub deletion_time: String, -} - -/// Whole database model (everything decrypted). -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct Database { - /// Format version as detected by [`crate::kdbx`] (`"3.1"` / `"4.0"` / `"4.1"`). - pub format_version: String, - /// ``. - pub meta: Meta, - /// Root group. - pub root: Group, - /// Deleted-object records. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub deleted_objects: Vec, - /// Unknown database-level XML. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub unknown: Vec, - /// Raw decrypted XML bytes (not serialized; may contain secrets). - /// - /// Kept so M1-02 does not lose data that the reader model does not map yet; - /// canonical dumps expose only its SHA-256, never the bytes. - #[serde(skip)] - pub raw_xml: Option>, - /// SHA-256 of [`Database::raw_xml`], included in canonical dumps as - /// evidence that unknown XML was preserved without leaking secrets. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub raw_xml_sha256: Option, -} - -impl Database { - /// Canonical JSON dump of the full model. - /// - /// Keys are emitted in struct order; deterministic collections use - /// `BTreeMap`/sorted keys. Structural order (groups/entries/strings) is kept - /// because it is meaningful for KeePass display and round-trip fidelity. - /// - /// Secret values (protected strings, `Password`, TOTP seeds) are replaced by - /// `sha256:` so a dump can be compared/logged without leaking them. - pub fn canonical_json(&self) -> Result { - let mut value = serde_json::to_value(self)?; - redact_value(&mut value); - serde_json::to_string_pretty(&value) - } - - /// Canonical JSON value (useful for tests/tools); secrets are redacted. - pub fn canonical_value(&self) -> Result { - let mut value = serde_json::to_value(self)?; - redact_value(&mut value); - Ok(value) - } -} - -fn is_secret_key(key: &str) -> bool { - key == "Password" - || key == "otp" - || key == "TOTP Seed" - || key.starts_with("TimeOtp-Secret") - || key.ends_with("_secret") -} - -fn redact_value(value: &mut serde_json::Value) { - match value { - serde_json::Value::Array(items) => { - for item in items { - redact_value(item); - } - } - serde_json::Value::Object(map) => { - let secret = map - .get("key") - .and_then(|key| key.as_str()) - .is_some_and(is_secret_key) - || map - .get("protected") - .and_then(|flag| flag.as_bool()) - .unwrap_or(false); - if secret { - if let Some(serde_json::Value::String(text)) = map.get_mut("value") { - let digest = sha2::Sha256::digest(text.as_bytes()); - let mut hex = String::with_capacity(digest.len() * 2); - for byte in digest { - hex.push_str(&format!("{byte:02x}")); - } - *text = format!("sha256:{hex}"); - } - if let Some(serde_json::Value::String(text)) = map.get_mut("password_secret") { - let digest = sha2::Sha256::digest(text.as_bytes()); - let mut hex = String::with_capacity(digest.len() * 2); - for byte in digest { - hex.push_str(&format!("{byte:02x}")); - } - *text = format!("sha256:{hex}"); - } - } - for child in map.values_mut() { - redact_value(child); - } - } - _ => {} - } -} - /// Hex encoding for byte arrays in canonical JSON. mod hex_bytes { use serde::{Deserialize, Deserializer, Serializer}; @@ -716,3 +104,21 @@ mod tests { assert!(canonical.contains("sha256:")); } } + +mod database; +mod entry; +mod group; +mod meta; +mod outer; +mod rawxml; +mod time; +mod uuid; + +pub use database::*; +pub use entry::*; +pub use group::*; +pub use meta::*; +pub use outer::*; +pub use rawxml::*; +pub use time::*; +pub use uuid::*; diff --git a/crates/core/src/model/outer.rs b/crates/core/src/model/outer.rs new file mode 100644 index 0000000..08732e1 --- /dev/null +++ b/crates/core/src/model/outer.rs @@ -0,0 +1,251 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! The outer header: ciphers, compression and KDF settings. + +use super::*; + +/// Outer KDBX cipher. Preserved from the source file so a save does not +/// silently switch algorithms. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OuterCipher { + Aes128, + Aes256, + Twofish, + ChaCha20, +} + +/// Outer KDBX compression. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OuterCompression { + None, + Gzip, +} + +/// Argon2 variant used by the source file. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Argon2Kind { + D, + Id, +} + +/// Key-derivation settings read from the source file. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum KdfSettings { + Aes { + rounds: u64, + }, + Argon2 { + kind: Argon2Kind, + iterations: u32, + memory_kib: u32, + parallelism: u32, + version: u32, + }, +} + +impl KdfSettings { + /// Upper bounds mirrored from the reader (`kdbx::reader`): this backend must + /// never write a file its own reader would refuse to open. + pub const MAX_AES_ROUNDS: u64 = 10_000_000; + pub const MAX_ARGON2_MEMORY_KIB: u32 = 2 * 1024 * 1024; + pub const MAX_ARGON2_ITERATIONS: u32 = 64; + pub const MAX_ARGON2_PARALLELISM: u32 = 16; + pub const MAX_ARGON2_WORK_MIB_ITERATIONS: u64 = 6_144; + + /// Reject configurations the reader would classify as extreme. + /// + /// The same checks run before every write, so a value that reaches the + /// writer through any path (preset, custom input, merge) cannot produce an + /// unreadable database. + pub fn validate(&self) -> Result<(), KdfError> { + match *self { + Self::Aes { rounds } => { + if rounds == 0 || rounds > Self::MAX_AES_ROUNDS { + return Err(KdfError::AesRounds { rounds }); + } + Ok(()) + } + Self::Argon2 { + iterations, + memory_kib, + parallelism, + .. + } => { + if parallelism == 0 || parallelism > Self::MAX_ARGON2_PARALLELISM { + return Err(KdfError::Argon2Parallelism { parallelism }); + } + let minimum_kib = 8u32.saturating_mul(parallelism); + if memory_kib < minimum_kib { + return Err(KdfError::Argon2MemoryTooSmall { + memory_kib, + parallelism, + }); + } + if memory_kib > Self::MAX_ARGON2_MEMORY_KIB { + return Err(KdfError::Argon2Memory { memory_kib }); + } + if iterations == 0 || iterations > Self::MAX_ARGON2_ITERATIONS { + return Err(KdfError::Argon2Iterations { iterations }); + } + let work = u64::from(memory_kib / 1024) * u64::from(iterations); + if work > Self::MAX_ARGON2_WORK_MIB_ITERATIONS { + return Err(KdfError::Argon2Work { + mib_iterations: work, + }); + } + Ok(()) + } + } + } + + /// Argon2 at or below 64 MiB is the level mobile clients open; AES-KDF needs + /// no extra memory at all. Above 64 MiB the database is desktop-only. + /// + /// This is a fact about other clients, not a recommendation: the app shows + /// it as the "compatibility" column and never changes the file on its own. + pub fn is_mobile_safe(&self) -> bool { + match *self { + Self::Aes { .. } => true, + Self::Argon2 { memory_kib, .. } => memory_kib <= 64 * 1024, + } + } +} + +/// Why a KDF configuration was rejected. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum KdfError { + /// AES-KDF round count outside `1..=MAX_AES_ROUNDS`. + AesRounds { rounds: u64 }, + /// Argon2 memory above the reader's limit. + Argon2Memory { memory_kib: u32 }, + /// Argon2 memory below the 8 KiB per lane minimum. + Argon2MemoryTooSmall { memory_kib: u32, parallelism: u32 }, + /// Argon2 iteration count outside `1..=MAX_ARGON2_ITERATIONS`. + Argon2Iterations { iterations: u32 }, + /// Argon2 lane count outside `1..=MAX_ARGON2_PARALLELISM`. + Argon2Parallelism { parallelism: u32 }, + /// Argon2 `memory (MiB) x iterations` above the work limit. + Argon2Work { mib_iterations: u64 }, +} + +impl fmt::Display for KdfError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::AesRounds { rounds } => write!( + f, + "AES-KDF round count {rounds} is outside 1..={}", + KdfSettings::MAX_AES_ROUNDS + ), + Self::Argon2Memory { memory_kib } => write!( + f, + "Argon2 memory {memory_kib} KiB is above the {} KiB limit", + KdfSettings::MAX_ARGON2_MEMORY_KIB + ), + Self::Argon2MemoryTooSmall { + memory_kib, + parallelism, + } => write!( + f, + "Argon2 memory {memory_kib} KiB is below the 8 KiB x {parallelism} lanes minimum" + ), + Self::Argon2Iterations { iterations } => write!( + f, + "Argon2 iteration count {iterations} is outside 1..={}", + KdfSettings::MAX_ARGON2_ITERATIONS + ), + Self::Argon2Parallelism { parallelism } => write!( + f, + "Argon2 parallelism {parallelism} is outside 1..={}", + KdfSettings::MAX_ARGON2_PARALLELISM + ), + Self::Argon2Work { mib_iterations } => write!( + f, + "Argon2 work {mib_iterations} MiB x iterations is above the {} limit", + KdfSettings::MAX_ARGON2_WORK_MIB_ITERATIONS + ), + } + } +} + +impl std::error::Error for KdfError {} + +/// Named KDF profiles offered to users. +/// +/// Every variant mirrors an external baseline or a plainly named strength tier; +/// none of them encodes a preference of this project. The UI renders the four +/// presets with two columns only (strength, compatibility) and never decides +/// for the user which one to keep. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum KdfPreset { + /// AES-KDF 600 000 rounds, the KeePass 2.x default. + KeepassClassic, + /// Argon2id 64 MiB / 3 / 2, the KeePassXC default order of magnitude. + KeepassXc, + /// Argon2id 128 MiB / 6 / 4, for desktop-only use. + Desktop, + /// Argon2id 256 MiB / 8 / 4, for desktop-only use. + Strong, +} + +impl KdfPreset { + /// Every preset, in the order the UI offers them. + pub const ALL: [Self; 4] = [ + Self::KeepassClassic, + Self::KeepassXc, + Self::Desktop, + Self::Strong, + ]; + + /// The settings this preset writes. + pub fn settings(self) -> KdfSettings { + match self { + Self::KeepassClassic => KdfSettings::Aes { rounds: 600_000 }, + Self::KeepassXc => KdfSettings::Argon2 { + kind: Argon2Kind::Id, + iterations: 3, + memory_kib: 64 * 1024, + parallelism: 2, + version: 0x13, + }, + Self::Desktop => KdfSettings::Argon2 { + kind: Argon2Kind::Id, + iterations: 6, + memory_kib: 128 * 1024, + parallelism: 4, + version: 0x13, + }, + Self::Strong => KdfSettings::Argon2 { + kind: Argon2Kind::Id, + iterations: 8, + memory_kib: 256 * 1024, + parallelism: 4, + version: 0x13, + }, + } + } +} + +/// KDBX4 outer header settings that must survive a save. Keeping these avoids +/// the old behaviour where every save rewrote a 4.1 file as 4.0 and replaced +/// the user's KDF (for example AES-KDF) with the writer's Argon2id default. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OuterHeader { + pub version: String, + pub cipher: OuterCipher, + pub compression: OuterCompression, + pub kdf: Option, + pub public_custom_data: Option>, +} + +impl OuterHeader { + /// Header settings used when the model has none yet: a database this app + /// creates, or a KDBX 3.1 source that is upgraded to 4.0 on save. + pub fn for_new_database() -> Self { + Self { + version: "4.0".to_string(), + cipher: OuterCipher::Aes256, + compression: OuterCompression::Gzip, + kdf: None, + public_custom_data: None, + } + } +} diff --git a/crates/core/src/model/rawxml.rs b/crates/core/src/model/rawxml.rs new file mode 100644 index 0000000..180dddb --- /dev/null +++ b/crates/core/src/model/rawxml.rs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Opaque XML kept verbatim so unknown elements survive a save. + +use super::*; + +/// Raw XML element preserved verbatim for unknown tags/attributes. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct RawXml { + /// Element name (e.g. `CustomPluginData`). + pub name: String, + /// Attributes in deterministic order. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub attributes: BTreeMap, + /// Direct text content, if any. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub text: Option, + /// Nested elements. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub children: Vec, +} + +impl RawXml { + /// Empty element with a name. + pub fn new(name: impl Into) -> Self { + Self { + name: name.into(), + ..Self::default() + } + } +} diff --git a/crates/core/src/model/time.rs b/crates/core/src/model/time.rs new file mode 100644 index 0000000..a8b665c --- /dev/null +++ b/crates/core/src/model/time.rs @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! KDBX timestamps and the XML date conversions. + +use super::*; + +/// KDBX times block. Strings keep the original XML date-time text so a rewrite +/// is byte-faithful; helpers convert to Unix seconds for DTOs. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Times { + /// `CreationTime`. + pub creation: String, + /// `LastModificationTime` — determines newness in merge. + pub last_modification: String, + /// `LastAccessTime`. + pub last_access: String, + /// `ExpiryTime` (only meaningful when `expires`). + pub expiry: String, + /// `Expires` flag. + pub expires: bool, + /// `UsageCount`. + pub usage_count: u64, + /// `LocationChanged` — determines latest location after a move. + pub location_changed: String, + /// Unknown child elements. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub unknown: Vec, +} + +impl Times { + /// Parsed `CreationTime` as Unix seconds. + pub fn created_unix(&self) -> Option { + xml_datetime_to_unix(&self.creation) + } + + /// Parsed `LastModificationTime` as Unix seconds. + pub fn modified_unix(&self) -> Option { + xml_datetime_to_unix(&self.last_modification) + } + + /// Parsed `LastAccessTime` as Unix seconds. + pub fn accessed_unix(&self) -> Option { + xml_datetime_to_unix(&self.last_access) + } + + /// Parsed `ExpiryTime` as Unix seconds when `expires` is set. + pub fn expires_unix(&self) -> Option { + if self.expires { + xml_datetime_to_unix(&self.expiry) + } else { + None + } + } +} + +/// Parse the KDBX UTC date-time format (`YYYY-MM-DDTHH:MM:SS[.fraction]Z`). +/// +/// Returns `None` for formats this minimal parser does not understand; callers +/// keep the raw string in that case. +pub fn xml_datetime_to_unix(value: &str) -> Option { + let bytes = value.as_bytes(); + if bytes.len() < 20 || bytes[4] != b'-' || bytes[7] != b'-' || bytes[10] != b'T' { + return None; + } + if bytes[13] != b':' || bytes[16] != b':' { + return None; + } + let year = value.get(0..4)?.parse::().ok()?; + let month = value.get(5..7)?.parse::().ok()?; + let day = value.get(8..10)?.parse::().ok()?; + let hour = value.get(11..13)?.parse::().ok()?; + let minute = value.get(14..16)?.parse::().ok()?; + let second = value.get(17..19)?.parse::().ok()?; + if !value.ends_with('Z') { + return None; + } + if !(1..=12).contains(&month) || !(1..=31).contains(&day) { + return None; + } + let days = days_from_civil(year, month, day); + Some(days * 86_400 + hour * 3_600 + minute * 60 + second) +} + +pub(crate) fn days_from_civil(year: i64, month: u32, day: u32) -> i64 { + let year = year - i64::from(month <= 2); + let era = if year >= 0 { year } else { year - 399 } / 400; + let year_of_era = year - era * 400; + let month = month as i64; + let day_of_year = (153 * (month + if month > 2 { -3 } else { 9 }) + 2) / 5 + day as i64 - 1; + let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; + era * 146_097 + day_of_era - 719_468 +} + +/// Format Unix seconds as the KDBX UTC date-time string +/// (`YYYY-MM-DDTHH:MM:SSZ`). +/// +/// The platform layer supplies the clock; this function is pure. +pub fn xml_datetime_from_unix(seconds: i64) -> String { + let days = seconds.div_euclid(86_400); + let second_of_day = seconds.rem_euclid(86_400); + let (year, month, day) = civil_from_days(days); + let hour = second_of_day / 3_600; + let minute = (second_of_day % 3_600) / 60; + let second = second_of_day % 60; + format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z") +} + +pub(crate) fn civil_from_days(days: i64) -> (i64, u32, u32) { + let z = days + 719_468; + let era = if z >= 0 { z } else { z - 146_096 } / 146_097; + let day_of_era = z - era * 146_097; + let year_of_era = + (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; + let year = year_of_era + era * 400; + let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); + let month_prime = (5 * day_of_year + 2) / 153; + let day = day_of_year - (153 * month_prime + 2) / 5 + 1; + let month = month_prime + if month_prime < 10 { 3 } else { -9 }; + let year = year + i64::from(month <= 2); + (year, month as u32, day as u32) +} diff --git a/crates/core/src/model/uuid.rs b/crates/core/src/model/uuid.rs new file mode 100644 index 0000000..7fe888d --- /dev/null +++ b/crates/core/src/model/uuid.rs @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! The KDBX UUID type and its display, parse and JSON forms. + +use super::*; + +/// 16-byte UUID as used by KDBX. Serialized as 32 lowercase hex characters. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +pub struct Uuid([u8; 16]); + +impl Uuid { + /// Create from raw bytes. + pub fn from_bytes(bytes: [u8; 16]) -> Self { + Self(bytes) + } + + /// All-zero UUID (KDBX "no value"). + pub fn nil() -> Self { + Self([0u8; 16]) + } + + /// Raw bytes. + pub fn as_bytes(&self) -> &[u8; 16] { + &self.0 + } + + /// `true` for the all-zero UUID. + pub fn is_nil(&self) -> bool { + self.0 == [0u8; 16] + } + + /// 32 lowercase hex characters. + pub fn to_hex(self) -> String { + let mut out = String::with_capacity(32); + for byte in self.0 { + out.push_str(&format!("{byte:02x}")); + } + out + } +} + +impl fmt::Display for Uuid { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.to_hex()) + } +} + +impl fmt::Debug for Uuid { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Uuid({})", self.to_hex()) + } +} + +impl FromStr for Uuid { + type Err = String; + + fn from_str(value: &str) -> Result { + let value = value.trim(); + let hex = value.replace('-', ""); + if hex.len() != 32 { + return Err(format!("invalid UUID length: {}", hex.len())); + } + let mut bytes = [0u8; 16]; + for (index, byte) in bytes.iter_mut().enumerate() { + let start = index * 2; + *byte = u8::from_str_radix(&hex[start..start + 2], 16) + .map_err(|_| format!("invalid UUID hex: {value}"))?; + } + Ok(Self(bytes)) + } +} + +impl Serialize for Uuid { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(&self.to_hex()) + } +} + +impl<'de> Deserialize<'de> for Uuid { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + value.parse().map_err(serde::de::Error::custom) + } +} diff --git a/crates/core/tests/kdf_defaults.rs b/crates/core/tests/kdf_defaults.rs index 94aedd6..cb8094f 100644 --- a/crates/core/tests/kdf_defaults.rs +++ b/crates/core/tests/kdf_defaults.rs @@ -1,28 +1,29 @@ // SPDX-License-Identifier: GPL-3.0-or-later //! Locks the Argon2id parameters used for databases this backend creates. //! -//! They are calibrated, not arbitrary: the v1.0 requirement asks for roughly -//! 0.5-1 s of KDF work per unlock on the reference machine. Measured with the -//! real reader (crates/core/tests/perf_paths_500.rs), 64 MiB / I=3 / P=2 -//! unlocked in ~0.32 s and 128 MiB / I=6 / P=4 in ~0.71 s, so the latter is the -//! default for files written by this backend (see `docs/compatibility.md` for -//! the user-facing write-format statement). +//! They are the interoperable baseline, not a calibration of this machine: a +//! database is shared across devices and the weakest client decides, so a new +//! file starts at 64 MiB / I=3 / P=2, the KeePassXC default order of magnitude. +//! Mobile clients (iOS AutoFill extensions in particular) have far less memory +//! than a desktop, and a database that cannot be opened on the phone is not +//! protected, it is broken. The stronger 128 MiB / 6 / 4 set remains available +//! as an explicit desktop-only choice (ADR-0031). //! -//! Existing databases keep the parameters recorded in their own header, so this -//! only affects new databases. If the default moves, this test and the -//! performance report must move together. +//! Existing databases keep the parameters recorded in their own header; changing +//! them is an explicit user action, never a side effect of saving +//! (`crates/core/tests/kdf_edit.rs` pins that). //! //! `default_argon2id` is the single source of truth in the vendored format //! crate; this test pins the values the product depends on so an accidental -//! vendor sync cannot silently weaken new vaults. +//! vendor sync cannot silently move them. use keepassxcr::crypto::{KdfConfig, KdfType}; /// A new database written through the product write path must carry the -/// calibrated parameters in its header (the header is what other KeePass -/// clients read), and that header must equal the backend default. +/// baseline parameters in its header (the header is what other KeePass clients +/// read), and that header must equal the backend default. #[test] -fn new_database_header_uses_the_calibrated_argon2id_parameters() { +fn new_database_header_uses_the_interoperable_argon2id_parameters() { let bytes = keepassity_core::kdbx::writer::create_empty("kdf-defaults-test", "kdf-defaults-test") .expect("create a new database"); @@ -54,13 +55,13 @@ fn new_database_header_uses_the_calibrated_argon2id_parameters() { assert_eq!(kind, default_kind); assert_eq!( memory_kib, - 128 * 1024, - "128 MiB: requirement lower bound is 64 MiB, 128 MiB measured at ~0.71 s" + 64 * 1024, + "64 MiB: the level mobile clients open, matching KeePassXC" ); assert_eq!(memory_kib, default_memory); - assert_eq!(iterations, 6, "I=6 measured inside the 0.5-1 s window"); + assert_eq!(iterations, 3, "I=3 keeps the unlock cost modest"); assert_eq!(iterations, default_iterations); - assert_eq!(parallelism, 4, "P=4 per REQUIREMENTS section 6.7"); + assert_eq!(parallelism, 2, "P=2 matches the 64 MiB KeePassXC profile"); assert_eq!(parallelism, default_parallelism); assert_eq!(version, 0x13, "Argon2 version 1.3 (0x13)"); assert_eq!(version, default_version); @@ -68,3 +69,33 @@ fn new_database_header_uses_the_calibrated_argon2id_parameters() { (written, default) => panic!("expected Argon2id headers, got {written:?} / {default:?}"), } } + +/// The presets the UI offers are the same values the core writes. +#[test] +fn presets_match_their_names_and_stay_inside_the_reader_limits() { + use keepassity_core::model::{KdfPreset, KdfSettings}; + + for preset in KdfPreset::ALL { + preset + .settings() + .validate() + .unwrap_or_else(|error| panic!("{preset:?} is not valid: {error}")); + } + + assert_eq!( + KdfPreset::KeepassClassic.settings(), + KdfSettings::Aes { rounds: 600_000 } + ); + assert_eq!( + KdfPreset::KeepassXc.settings(), + KdfSettings::Argon2 { + kind: keepassity_core::model::Argon2Kind::Id, + iterations: 3, + memory_kib: 64 * 1024, + parallelism: 2, + version: 0x13, + } + ); + assert!(KdfPreset::KeepassXc.settings().is_mobile_safe()); + assert!(!KdfPreset::Desktop.settings().is_mobile_safe()); +} diff --git a/crates/core/tests/kdf_edit.rs b/crates/core/tests/kdf_edit.rs new file mode 100644 index 0000000..0605316 --- /dev/null +++ b/crates/core/tests/kdf_edit.rs @@ -0,0 +1,144 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Changing a database's KDF is an explicit edit that must reach the header. +//! +//! The write backend takes the KDF from the save cache, so a save that reuses a +//! cache derived for the old parameters would silently keep them. These tests +//! pin both paths (change then save with and without a stale cache), the +//! untouched preserve path, and the validation gate that keeps this backend from +//! writing a file its own reader would refuse. + +use keepassity_core::kdbx::{reader, writer}; +use keepassity_core::model::{Argon2Kind, Database, KdfError, KdfPreset, KdfSettings}; + +const PASSWORD: &str = "kdf-edit-test"; +/// The parameters a new database starts with (ADR-0031 interoperable baseline). +const DEFAULT_ARGON2ID: KdfSettings = KdfSettings::Argon2 { + kind: Argon2Kind::Id, + iterations: 3, + memory_kib: 64 * 1024, + parallelism: 2, + version: 0x13, +}; + +fn new_database() -> Database { + let bytes = writer::create_empty("kdf-edit", PASSWORD).expect("create a database"); + reader::parse(&bytes, PASSWORD).expect("parse the new database") +} + +fn header_kdf(db: &Database) -> KdfSettings { + db.outer + .as_ref() + .and_then(|header| header.kdf.clone()) + .expect("a KDBX 4 database carries a KDF in its header") +} + +#[test] +fn every_preset_reaches_the_saved_header() { + for preset in KdfPreset::ALL { + let mut db = new_database(); + let wanted = preset.settings(); + db.set_kdf(wanted.clone()).expect("preset is valid"); + let bytes = writer::write_model(&db, PASSWORD).expect("write"); + let reopened = reader::parse(&bytes, PASSWORD).expect("reopen"); + assert_eq!(header_kdf(&reopened), wanted, "preset {preset:?}"); + } +} + +#[test] +fn a_stale_cache_does_not_override_a_new_kdf() { + let mut db = new_database(); + db.set_kdf(KdfPreset::KeepassXc.settings()).expect("valid"); + let (_, cache) = writer::write_model_cached(&db, PASSWORD, None).expect("first save"); + + let wanted = KdfPreset::Strong.settings(); + db.set_kdf(wanted.clone()).expect("valid"); + // Hand the writer the cache derived for the previous parameters: it must let + // go of it and derive again, otherwise the header keeps the old 64 MiB. + let (bytes, _) = writer::write_model_cached(&db, PASSWORD, Some(&cache)).expect("second save"); + + let reopened = reader::parse(&bytes, PASSWORD).expect("reopen"); + assert_eq!( + header_kdf(&reopened), + wanted, + "a stale KDF cache must not win over an explicit edit" + ); +} + +#[test] +fn an_unchanged_kdf_keeps_reusing_the_cache() { + let mut db = new_database(); + db.set_kdf(KdfPreset::KeepassXc.settings()).expect("valid"); + let (_, cache) = writer::write_model_cached(&db, PASSWORD, None).expect("first save"); + let (bytes, _) = writer::write_model_cached(&db, PASSWORD, Some(&cache)).expect("second save"); + let reopened = reader::parse(&bytes, PASSWORD).expect("reopen"); + assert_eq!(header_kdf(&reopened), KdfPreset::KeepassXc.settings()); +} + +#[test] +fn saving_without_an_edit_preserves_the_source_parameters() { + let mut db = new_database(); + db.set_kdf(KdfSettings::Aes { rounds: 600_000 }) + .expect("valid"); + let bytes = writer::write_model(&db, PASSWORD).expect("write"); + let reopened = reader::parse(&bytes, PASSWORD).expect("reopen"); + assert_eq!(header_kdf(&reopened), KdfSettings::Aes { rounds: 600_000 }); + + let second = writer::write_model(&reopened, PASSWORD).expect("second write"); + let reopened_again = reader::parse(&second, PASSWORD).expect("reopen again"); + assert_eq!( + header_kdf(&reopened_again), + KdfSettings::Aes { rounds: 600_000 }, + "a save without an edit must not rewrite the KDF" + ); +} + +#[test] +fn extreme_parameters_are_rejected_before_they_can_be_written() { + let mut db = new_database(); + let error = db + .set_kdf(KdfSettings::Argon2 { + kind: Argon2Kind::Id, + iterations: 1, + memory_kib: 3 * 1024 * 1024, + parallelism: 2, + version: 0x13, + }) + .expect_err("3 GiB exceeds the reader limit"); + assert!(matches!(error, KdfError::Argon2Memory { .. })); + assert_eq!( + header_kdf(&db), + DEFAULT_ARGON2ID, + "a rejected edit must leave the model untouched" + ); +} + +/// The owner's database shape: KDBX 4.1 with AES-KDF. Restoring that profile and +/// switching to the mobile profile must both keep the 4.1 outer format, which is +/// what an older save of the real vault destroyed. +#[test] +fn a_kdbx41_source_keeps_its_version_while_the_kdf_changes() { + let bytes = std::fs::read(format!( + "{}/../../tests/fixtures/keepass-rs/test_db_kdbx41_with_password_aes.kdbx", + env!("CARGO_MANIFEST_DIR") + )) + .expect("4.1 fixture"); + let mut db = reader::parse(&bytes, "demopass").expect("fixture opens"); + assert_eq!(db.format_version, "4.1"); + + db.set_kdf(KdfPreset::KeepassClassic.settings()) + .expect("600 000 AES-KDF rounds are valid"); + let restored = writer::write_model(&db, "demopass").expect("write"); + let reopened = reader::parse(&restored, "demopass").expect("reopen"); + assert_eq!( + reopened.format_version, "4.1", + "restoring the parameters must not downgrade the outer format" + ); + assert_eq!(header_kdf(&reopened), KdfPreset::KeepassClassic.settings()); + + let mut db = reopened; + db.set_kdf(KdfPreset::KeepassXc.settings()).expect("valid"); + let mobile = writer::write_model(&db, "demopass").expect("write"); + let reopened = reader::parse(&mobile, "demopass").expect("reopen"); + assert_eq!(reopened.format_version, "4.1"); + assert_eq!(header_kdf(&reopened), KdfPreset::KeepassXc.settings()); +} diff --git a/crates/core/tests/malformed_input.rs b/crates/core/tests/malformed_input.rs index 11b15b0..87e0ff2 100644 --- a/crates/core/tests/malformed_input.rs +++ b/crates/core/tests/malformed_input.rs @@ -57,6 +57,82 @@ fn extreme_kdf_parameters_are_rejected_quickly() { ); } +fn variant_entry(value_type: u8, key: &[u8], value: &[u8]) -> Vec { + let mut entry = vec![value_type]; + entry.extend_from_slice(&(key.len() as u32).to_le_bytes()); + entry.extend_from_slice(key); + entry.extend_from_slice(&(value.len() as u32).to_le_bytes()); + entry.extend_from_slice(value); + entry +} + +fn aes_kdf_dictionary(rounds: u64) -> Vec { + const UUID_AES: [u8; 16] = [ + 0xC9, 0xD9, 0xF3, 0x9A, 0x62, 0x8A, 0x44, 0x60, 0xBF, 0x74, 0x0D, 0x08, 0xC1, 0x8A, 0x4F, + 0xEA, + ]; + let mut dictionary = vec![0x00, 0x01]; + // KDBX 4 stores `$UUID` as VariantDictionary ByteArray (0x42). + dictionary.extend_from_slice(&variant_entry(0x42, b"$UUID", &UUID_AES)); + dictionary.extend_from_slice(&variant_entry(0x05, b"R", &rounds.to_le_bytes())); + dictionary.push(0); + dictionary +} + +fn kdbx4_header(dictionaries: &[Vec]) -> Vec { + let mut bytes = vec![ + 0x03, 0xD9, 0xA2, 0x9A, 0x67, 0xFB, 0x4B, 0xB5, 0x00, 0x00, 0x04, 0x00, + ]; + for dictionary in dictionaries { + bytes.push(0x0B); + bytes.extend_from_slice(&(dictionary.len() as u32).to_le_bytes()); + bytes.extend_from_slice(dictionary); + } + bytes.push(0x00); + bytes.extend_from_slice(&4u32.to_le_bytes()); + bytes.extend_from_slice(&[0x0D, 0x0A, 0x0D, 0x0A]); + bytes +} + +/// Legal KDBX 4 uses a ByteArray `$UUID`. A file that asks for 30M AES-KDF +/// rounds through that shape must be rejected before the key derivation runs. +#[test] +fn kdbx4_byte_array_kdf_with_extreme_rounds_is_rejected_quickly() { + let bytes = kdbx4_header(&[aes_kdf_dictionary(30_000_000)]); + let started = std::time::Instant::now(); + let result = keepassity_core::kdbx::reader::parse(&bytes, "demopass"); + let elapsed = started.elapsed(); + match result { + Err(keepassity_core::kdbx::reader::KdbxReadError::Unsupported(message)) => { + assert!( + message.contains("extreme") && message.contains("AES-KDF"), + "unexpected safety-limit reason: {message}" + ); + } + Err(other) => panic!("expected the KDF safety-limit error, got {other:?}"), + Ok(_) => panic!("an extreme-KDF file must never parse"), + } + assert!( + elapsed < std::time::Duration::from_secs(2), + "rejecting the file must not spend the KDF time (took {elapsed:?})" + ); +} + +/// Two KDF-parameters fields would let keepass use the last one while a +/// one-pass validator inspected the first. Reject the ambiguous header. +#[test] +fn duplicate_kdbx4_kdf_header_fields_are_rejected() { + let bytes = kdbx4_header(&[aes_kdf_dictionary(600_000), aes_kdf_dictionary(30_000_000)]); + let result = keepassity_core::kdbx::reader::parse(&bytes, "demopass"); + assert!( + matches!( + result, + Err(keepassity_core::kdbx::reader::KdbxReadError::Header(_)) + ), + "duplicate KDF fields must be a header error, got {result:?}" + ); +} + /// A truncated file (shorter than the 12-byte header) is also a read error. #[test] fn short_input_is_a_header_error() { diff --git a/crates/core/tests/merge_history_deletions.rs b/crates/core/tests/merge_history_deletions.rs new file mode 100644 index 0000000..6299423 --- /dev/null +++ b/crates/core/tests/merge_history_deletions.rs @@ -0,0 +1,337 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! KeePass merge semantics for DeletedObjects, history retention and group +//! subtrees. These are regressions for the old behaviour that applied every +//! deletion unconditionally and ignored `deletion_time`, silently discarding a +//! local edit (with no conflict and no history). + +use keepassity_core::merge::{merge, ConflictKind}; +use keepassity_core::model::{Database, DeletedObject, Entry, Group, StringField, Times, Uuid}; + +fn uuid(byte: u8) -> Uuid { + Uuid::from_bytes([byte; 16]) +} + +fn stamp(second: u8) -> String { + format!("2026-10-26T00:00:{second:02}Z") +} + +fn entry(byte: u8, title: &str, modified: u8, location: u8) -> Entry { + let mut entry = Entry { + uuid: uuid(byte), + times: Times { + creation: stamp(1), + last_modification: stamp(modified), + last_access: stamp(modified), + location_changed: stamp(location), + ..Times::default() + }, + ..Entry::default() + }; + entry.strings.push(StringField { + key: "Title".to_string(), + value: title.to_string(), + protected: false, + unknown: Vec::new(), + }); + entry +} + +fn group(byte: u8, name: &str, modified: u8) -> Group { + Group { + uuid: uuid(byte), + name: name.to_string(), + times: Times { + creation: stamp(1), + last_modification: stamp(modified), + last_access: stamp(modified), + location_changed: stamp(1), + ..Times::default() + }, + ..Group::default() + } +} + +fn database() -> Database { + Database { + root: Group { + uuid: uuid(1), + name: "Root".to_string(), + ..Group::default() + }, + ..Database::default() + } +} + +fn delete_record(byte: u8, second: u8) -> DeletedObject { + DeletedObject { + uuid: uuid(byte), + deletion_time: stamp(second), + } +} + +fn child_group(db: &Database, byte: u8) -> Option<&Group> { + db.root.groups.iter().find(|group| group.uuid == uuid(byte)) +} + +#[test] +fn remote_delete_after_local_modification_keeps_entry_and_conflicts() { + let local = { + let mut db = database(); + db.root.entries.push(entry(2, "local-edit", 10, 2)); + db + }; + let mut remote = database(); + remote.deleted_objects.push(delete_record(2, 5)); + + let (merged, report) = merge(&local, &remote); + + let entry = merged + .root + .entries + .iter() + .find(|entry| entry.uuid == uuid(2)) + .expect("the later local edit must survive"); + assert_eq!(entry.field("Title"), Some("local-edit")); + + assert_eq!(report.conflicts, 1); + assert_eq!(report.conflict_items.len(), 1); + let conflict = &report.conflict_items[0]; + assert_eq!(conflict.uuid, uuid(2)); + assert_eq!(conflict.kind, ConflictKind::Entry); + assert_eq!( + conflict.fields, + vec!["deleted remotely but modified locally".to_string()] + ); + assert_eq!(conflict.local_modified, stamp(10)); + assert_eq!(conflict.remote_modified, stamp(5)); + assert!( + !merged + .deleted_objects + .iter() + .any(|item| item.uuid == uuid(2)), + "a deletion that was not applied must not remain in the merged output" + ); +} + +#[test] +fn local_delete_after_remote_modification_keeps_entry_and_conflicts() { + let mut local = database(); + local.deleted_objects.push(delete_record(2, 5)); + let remote = { + let mut db = database(); + db.root.entries.push(entry(2, "remote-edit", 10, 2)); + db + }; + + let (merged, report) = merge(&local, &remote); + + let entry = merged + .root + .entries + .iter() + .find(|entry| entry.uuid == uuid(2)) + .expect("the later remote edit must survive"); + assert_eq!(entry.field("Title"), Some("remote-edit")); + + assert_eq!(report.conflicts, 1); + let conflict = &report.conflict_items[0]; + assert_eq!(conflict.kind, ConflictKind::Entry); + assert_eq!( + conflict.fields, + vec!["deleted locally but modified remotely".to_string()] + ); + assert_eq!(conflict.local_modified, stamp(5)); + assert_eq!(conflict.remote_modified, stamp(10)); +} + +#[test] +fn deletion_at_or_after_modification_applies() { + // Remote deletion at the same time or later than the edit -> delete. + for deletion_second in [5, 6] { + let mut local = database(); + local.root.entries.push(entry(2, "old", 5, 2)); + let mut remote = database(); + remote + .deleted_objects + .push(delete_record(2, deletion_second)); + + let (merged, report) = merge(&local, &remote); + assert!( + merged + .root + .entries + .iter() + .all(|entry| entry.uuid != uuid(2)), + "deletion at {deletion_second} must remove an edit at 5" + ); + assert_eq!(report.conflicts, 0); + assert!(merged + .deleted_objects + .iter() + .any(|item| item.uuid == uuid(2))); + } + + // Local deletes before the remote edit -> the edit survives. + let mut local = database(); + local.deleted_objects.push(delete_record(2, 5)); + let mut remote = database(); + remote.root.entries.push(entry(2, "newer", 6, 2)); + + let (merged, report) = merge(&local, &remote); + assert!(merged + .root + .entries + .iter() + .any(|entry| entry.uuid == uuid(2))); + assert_eq!(report.conflicts, 1); +} + +#[test] +fn group_deleted_remotely_but_modified_locally_is_kept_and_conflicts() { + let mut local = database(); + local.root.groups.push(group(3, "local-renamed", 10)); + let mut remote = database(); + remote.root.groups.push(group(3, "old", 4)); + remote.deleted_objects.push(delete_record(3, 5)); + + let (merged, report) = merge(&local, &remote); + + let group = child_group(&merged, 3).expect("the later local rename must survive"); + assert_eq!(group.name, "local-renamed"); + assert_eq!(report.conflicts, 1); + let conflict = &report.conflict_items[0]; + assert_eq!(conflict.uuid, uuid(3)); + assert_eq!(conflict.kind, ConflictKind::Group); + assert_eq!( + conflict.fields, + vec!["deleted remotely but modified locally".to_string()] + ); + assert_eq!(conflict.local_modified, stamp(10)); + assert_eq!(conflict.remote_modified, stamp(5)); +} + +#[test] +fn deleted_group_with_a_later_local_edit_survives_with_its_content() { + let mut local = database(); + let mut doomed = group(3, "Doomed", 2); + doomed + .entries + .push(entry(2, "edited-after-deletion", 10, 2)); + local.root.groups.push(doomed); + let mut remote = database(); + remote.deleted_objects.push(delete_record(3, 5)); + + let (merged, report) = merge(&local, &remote); + + let group = child_group(&merged, 3) + .expect("a deleted group holding surviving content must not be removed"); + assert_eq!(group.name, "Doomed"); + assert_eq!( + group + .entries + .iter() + .find(|entry| entry.uuid == uuid(2)) + .and_then(|entry| entry.field("Title")), + Some("edited-after-deletion") + ); + assert!( + !merged + .deleted_objects + .iter() + .any(|item| item.uuid == uuid(3)), + "the group deletion was not applied, so its record must not be output" + ); + assert_eq!(report.conflicts, 0, "the group itself was not edited"); +} + +#[test] +fn duplicate_deletion_records_keep_the_latest_time() { + let mut local = database(); + // Same UUID twice: only the later deletion (7) may be used. The remote + // entry was modified at 6, so it must be deleted. + local.deleted_objects.push(delete_record(2, 5)); + local.deleted_objects.push(delete_record(2, 7)); + let mut remote = database(); + remote.root.entries.push(entry(2, "six", 6, 2)); + + let (merged, report) = merge(&local, &remote); + + assert!(!merged + .root + .entries + .iter() + .any(|entry| entry.uuid == uuid(2))); + let record = merged + .deleted_objects + .iter() + .find(|item| item.uuid == uuid(2)) + .expect("deletion record"); + assert_eq!(record.deletion_time, stamp(7)); + assert_eq!(report.deleted_skipped, 1); + + // A later record on the remote side also wins over an earlier local one. + let mut local = database(); + local.deleted_objects.push(delete_record(4, 7)); + let mut remote = database(); + remote.root.entries.push(entry(4, "six", 6, 2)); + remote.deleted_objects.push(delete_record(4, 5)); + let (merged, _) = merge(&local, &remote); + assert!(!merged + .root + .entries + .iter() + .any(|entry| entry.uuid == uuid(4))); +} + +#[test] +fn merged_history_is_truncated_to_local_item_limit() { + let mut local = database(); + local.meta.history_max_items = 1; + local.meta.history_max_size = -1; + let mut current = entry(2, "v1", 2, 2); + current.history.push(entry(2, "v0", 1, 1)); + local.root.entries.push(current); + let mut remote = database(); + remote.root.entries.push(entry(2, "v2", 3, 2)); + + let (merged, report) = merge(&local, &remote); + + let entry = &merged.root.entries[0]; + assert_eq!(entry.field("Title"), Some("v2")); + assert_eq!( + entry.history.len(), + 1, + "the 10-item default must be overridden by the local limit" + ); + assert_eq!(entry.history[0].field("Title"), Some("v1")); + assert_eq!(report.conflicts, 0); +} + +#[test] +fn merged_history_is_truncated_to_local_size_limit() { + let mut local = database(); + local.meta.history_max_items = -1; + local.meta.history_max_size = 0; + let mut current = entry(2, "v1", 2, 2); + current.history.push(entry(2, "v0", 1, 1)); + local.root.entries.push(current); + let mut remote = database(); + remote.root.entries.push(entry(2, "v2", 3, 2)); + + let (merged, _) = merge(&local, &remote); + + let entry = &merged.root.entries[0]; + assert_eq!(entry.field("Title"), Some("v2")); + assert!( + entry.history.is_empty(), + "a zero size limit must keep no history after merge" + ); +} + +#[test] +fn default_database_meta_uses_keepass_history_defaults() { + let db = Database::default(); + assert!(db.meta.recycle_bin_enabled); + assert_eq!(db.meta.history_max_items, 10); + assert_eq!(db.meta.history_max_size, 6 * 1024 * 1024); +} diff --git a/crates/core/tests/merge_write.rs b/crates/core/tests/merge_write.rs index 7ea5261..c131737 100644 --- a/crates/core/tests/merge_write.rs +++ b/crates/core/tests/merge_write.rs @@ -14,7 +14,14 @@ fn fixture() -> PathBuf { fn write_and_read(db: &Database) -> Database { let bytes = writer::write_model(db, "test").expect("write merged model"); - assert_eq!(detect_version(&bytes[..12]).unwrap().as_str(), "4.0"); + let version = detect_version(&bytes[..12]).unwrap().as_str(); + if let Some(outer) = &db.outer { + // A save preserves the source KDBX4 version; only databases without an + // outer header (created in memory) use the 4.0 write default. + assert_eq!(version, outer.version); + } else { + assert_eq!(version, "4.0"); + } reader::parse(&bytes, "test").expect("read written model") } diff --git a/crates/core/tests/model_dto.rs b/crates/core/tests/model_dto.rs index c92c5f0..1bb6ddc 100644 --- a/crates/core/tests/model_dto.rs +++ b/crates/core/tests/model_dto.rs @@ -153,6 +153,7 @@ fn full_database() -> Database { Database { format_version: "4.1".into(), + outer: None, meta, root: group, deleted_objects: vec![DeletedObject { diff --git a/crates/core/tests/synthetic_fixture.rs b/crates/core/tests/synthetic_fixture.rs index 408b449..9aa30d1 100644 --- a/crates/core/tests/synthetic_fixture.rs +++ b/crates/core/tests/synthetic_fixture.rs @@ -220,6 +220,7 @@ pub fn synthetic_database() -> Database { .collect(); Database { format_version: "4.0".to_string(), + outer: None, meta: Meta { database_name: "Synthetic 500".to_string(), database_description: "Synthetic 500-entry fixture generated by \ diff --git a/crates/core/tests/writer_fidelity.rs b/crates/core/tests/writer_fidelity.rs new file mode 100644 index 0000000..518ae72 --- /dev/null +++ b/crates/core/tests/writer_fidelity.rs @@ -0,0 +1,287 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Write-fidelity and sync-conflict regression checks. +//! +//! `write_model` is used after every save and merge, so everything the reader +//! parsed must survive a rewrite. A rewrite that silently drops data (icons, +//! auto-type, colors, custom data, group notes, ...) changes the entry +//! fingerprints and makes the next merge against a vault written by another +//! client report a conflict for content the user never touched. + +use keepassity_core::kdbx::{reader, writer}; +use keepassity_core::merge::merge; +use keepassity_core::model::{Database, Entry, Group}; +use std::path::{Path, PathBuf}; + +const PASSWORD: &str = "demopass"; + +fn fixtures() -> Vec { + let base = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/keepass-rs"); + [ + "test_db_kdbx4_with_password_aes.kdbx", + "test_db_kdbx41_features.kdbx", + "test_db_with_password.kdbx", + ] + .iter() + .map(|name| base.join(name)) + .collect() +} + +fn parse_fixture(path: &Path) -> Database { + let bytes = std::fs::read(path).expect("fixture bytes"); + reader::parse(&bytes, PASSWORD).expect("parse fixture") +} + +fn rewrite(db: &Database) -> Database { + let bytes = writer::write_model(db, PASSWORD).expect("write model"); + reader::parse(&bytes, PASSWORD).expect("read back") +} + +/// `Generator` is written by the backend itself, so it is not part of the +/// model round trip. +fn comparable(mut db: Database) -> Database { + // Written by the backend itself, or diagnostics of the last read. + db.meta.generator = String::new(); + db.format_version = String::new(); + db.raw_xml = None; + db.raw_xml_sha256 = None; + db +} + +fn describe_differences(left: &Database, right: &Database) -> Vec { + fn diff_paths(a: &serde_json::Value, b: &serde_json::Value, path: &str, out: &mut Vec) { + match (a, b) { + (serde_json::Value::Object(ma), serde_json::Value::Object(mb)) => { + for key in ma.keys().chain(mb.keys()) { + let pa = ma.get(key); + let pb = mb.get(key); + if pa != pb { + let child = format!("{path}/{key}"); + match (pa, pb) { + (Some(pa), Some(pb)) => diff_paths(pa, pb, &child, out), + _ => out.push(child), + } + } + } + } + (serde_json::Value::Array(va), serde_json::Value::Array(vb)) => { + if va.len() != vb.len() { + out.push(format!("{path}[len {} vs {}]", va.len(), vb.len())); + return; + } + for (index, (ca, cb)) in va.iter().zip(vb.iter()).enumerate() { + if ca != cb { + diff_paths(ca, cb, &format!("{path}[{index}]"), out); + } + } + } + _ => { + if a != b { + out.push(path.to_string()); + } + } + } + } + let a = serde_json::to_value(left).expect("json"); + let b = serde_json::to_value(right).expect("json"); + let mut out = Vec::new(); + diff_paths(&a, &b, "", &mut out); + out +} + +/// Merge intentionally unions and deduplicates history snapshots, so compare +/// the current content only. +fn without_history(mut db: Database) -> Database { + fn clear(group: &mut Group) { + for entry in &mut group.entries { + entry.history.clear(); + } + for child in &mut group.groups { + clear(child); + } + } + clear(&mut db.root); + db +} + +fn first_entry_mut(group: &mut Group) -> Option<&mut Entry> { + if let Some(entry) = group.entries.first_mut() { + return Some(entry); + } + group.groups.iter_mut().find_map(first_entry_mut) +} + +#[test] +fn write_model_keeps_every_field_the_reader_parsed() { + for path in fixtures() { + let original = parse_fixture(&path); + let again = rewrite(&original); + let differences = + describe_differences(&comparable(again.clone()), &comparable(original.clone())); + assert!( + differences.is_empty(), + "rewriting {} lost data: {:?}", + path.display(), + differences + ); + } +} + +#[test] +fn rewriting_a_vault_does_not_introduce_merge_conflicts() { + for path in fixtures() { + let original = parse_fixture(&path); + let rewritten = rewrite(&original); + let (merged, report) = merge(&rewritten, &original); + assert_eq!( + report.conflicts, + 0, + "{}: a rewrite must not look like a concurrent edit", + path.display() + ); + // The same check in the other direction: local file vs remote copy. + let (_, reversed) = merge(&original, &rewritten); + assert_eq!(reversed.conflicts, 0, "{}: reversed order", path.display()); + let differences = describe_differences( + &comparable(without_history(merged)), + &comparable(without_history(rewritten.clone())), + ); + assert!( + differences.is_empty(), + "{}: merging with the untouched original must keep the vault as is: {:?}", + path.display(), + differences + ); + } +} + +/// Simulates the vault files our own earlier builds wrote (and any client that +/// omits optional metadata): same content, no icons, colors, auto-type or +/// custom data. +fn strip_optional_metadata(mut db: Database) -> Database { + fn strip_entry(entry: &mut Entry) { + entry.icon_id = 0; + entry.custom_icon_uuid = None; + entry.foreground_color.clear(); + entry.background_color.clear(); + entry.override_url.clear(); + entry.auto_type = None; + entry.custom_data = Default::default(); + for history in &mut entry.history { + strip_entry(history); + } + } + fn strip_group(group: &mut Group) { + group.notes.clear(); + group.icon_id = 0; + group.custom_icon_uuid = None; + group.is_expanded = false; + group.default_autotype_sequence.clear(); + group.enable_auto_type = false; + group.enable_searching = false; + group.last_top_visible_entry = None; + group.custom_data = Default::default(); + for entry in &mut group.entries { + strip_entry(entry); + } + for child in &mut group.groups { + strip_group(child); + } + } + strip_group(&mut db.root); + db +} + +#[test] +fn a_vault_saved_by_an_older_build_merges_without_asking() { + for path in fixtures() { + let original = parse_fixture(&path); + let stripped = strip_optional_metadata(original.clone()); + for (local, remote) in [(&stripped, &original), (&original, &stripped)] { + let (merged, report) = merge(local, remote); + assert_eq!( + report.conflicts, + 0, + "{}: missing optional metadata must not look like an edit", + path.display() + ); + let differences = describe_differences( + &comparable(without_history(merged)), + &comparable(without_history(original.clone())), + ); + assert!( + differences.is_empty(), + "{}: the richer copy must win: {:?}", + path.display(), + differences + ); + } + } +} + +#[test] +fn different_metadata_on_both_sides_still_conflicts() { + let original = parse_fixture(&fixtures()[0]); + let mut local = original.clone(); + let mut remote = original.clone(); + first_entry_mut(&mut local.root).expect("entry").icon_id = 5; + first_entry_mut(&mut remote.root).expect("entry").icon_id = 7; + let (_, report) = merge(&local, &remote); + assert_eq!( + report.conflicts, 1, + "two different icons are a real edit and must ask the user" + ); +} + +#[test] +fn a_real_content_change_at_the_same_time_still_conflicts() { + let original = parse_fixture(&fixtures()[0]); + let mut remote = original.clone(); + let entry = first_entry_mut(&mut remote.root).expect("entry"); + entry.strings.retain(|field| field.key != "Title"); + entry.strings.push(keepassity_core::model::StringField { + key: "Title".to_string(), + value: "changed elsewhere".to_string(), + protected: false, + unknown: Vec::new(), + }); + let (_, report) = merge(&original, &remote); + assert_eq!( + report.conflicts, 1, + "a same-time content change must still ask the user" + ); +} + +#[test] +fn a_move_to_the_top_level_survives_a_rewrite_and_merge() { + let mut local = parse_fixture(&fixtures()[0]); + let (entry_uuid, _) = first_entry_mut(&mut local.root) + .map(|entry| (entry.uuid, ())) + .expect("entry"); + // Mimic the FFI move handler: remove, bump LocationChanged, append to root. + fn take(group: &mut Group, uuid: keepassity_core::model::Uuid) -> Option { + if let Some(index) = group.entries.iter().position(|entry| entry.uuid == uuid) { + return Some(group.entries.remove(index)); + } + for child in &mut group.groups { + if let Some(entry) = take(child, uuid) { + return Some(entry); + } + } + None + } + let mut entry = take(&mut local.root, entry_uuid).expect("entry exists"); + entry.times.location_changed = "2026-11-10T10:00:00Z".to_string(); + local.root.entries.push(entry); + + let rewritten = rewrite(&local); + let (merged, report) = merge(&rewritten, &local); + assert_eq!(report.conflicts, 0, "the move must not conflict"); + assert!( + merged + .root + .entries + .iter() + .any(|entry| entry.uuid == entry_uuid), + "the moved entry must stay at the top level" + ); +} diff --git a/crates/core/tests/writer_header.rs b/crates/core/tests/writer_header.rs new file mode 100644 index 0000000..29616fc --- /dev/null +++ b/crates/core/tests/writer_header.rs @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! A save must preserve the KDBX4 outer header the user's file arrived with. +//! +//! Regression for the old writer, which built a fresh `KdbxFile::new` on every +//! save: a 4.1 file was written back as 4.0 and an AES-KDF database was +//! silently converted to Argon2id, changing open time and compatibility. + +use keepassity_core::kdbx::reader::parse; +use keepassity_core::kdbx::save::verify_rewritten; +use keepassity_core::kdbx::writer::{verify_written_with_cache, write_model, write_model_cached}; +use keepassity_core::merge::merge; +use keepassxcr::format::read_kdbx_bytes; +use keepassxcr::Credentials; + +fn fixture(name: &str) -> Vec { + std::fs::read(format!( + "{}/../../tests/fixtures/keepass-rs/{name}", + env!("CARGO_MANIFEST_DIR") + )) + .expect("fixture") +} + +#[test] +fn save_preserves_the_outer_header() { + for name in [ + "test_db_kdbx4_with_password_aes.kdbx", + "test_db_kdbx4_with_password_argon2id.kdbx", + "test_db_kdbx4_with_password_argon2_chacha20.kdbx", + "test_db_kdbx4_with_password_argon2_twofish.kdbx", + "test_db_kdbx4_with_password_argon2id_chacha20.kdbx", + "test_db_kdbx4_with_password_argon2id_twofish.kdbx", + "test_db_kdbx41_features.kdbx", + ] { + let database = parse(&fixture(name), "demopass").expect("read fixture"); + let header = database + .outer + .clone() + .unwrap_or_else(|| panic!("{name}: no outer header")); + assert_eq!(database.format_version, header.version, "{name}"); + + let written = write_model(&database, "demopass").expect("write model"); + let reread = parse(&written, "demopass").expect("read written model"); + assert_eq!( + reread.format_version, header.version, + "{name}: version changed" + ); + assert_eq!( + reread.outer.as_ref(), + Some(&header), + "{name}: outer header changed" + ); + } +} + +#[test] +fn merge_preserves_the_outer_header() { + let database = + parse(&fixture("test_db_kdbx4_with_password_aes.kdbx"), "demopass").expect("read fixture"); + let (merged, report) = merge(&database, &database); + assert_eq!(report.conflicts, 0); + assert_eq!(merged.outer, database.outer); +} + +#[test] +fn a_written_database_passes_verified_rewrite() { + // The old writer reset the header, so verify_rewritten rejected every + // output. The preserved header is what makes the core save protocol usable. + let original = fixture("test_db_kdbx4_with_password_aes.kdbx"); + let database = parse(&original, "demopass").expect("read fixture"); + let written = write_model(&database, "demopass").expect("write model"); + verify_rewritten(&original, &written, "demopass").expect("verified rewrite"); +} + +#[test] +fn cached_saves_reuse_the_kdf_salt() { + // The first save derives the transformed key and returns a cache; the + // second save must reuse the same KDF salt/transformed key instead of + // running the KDF again, while still drawing a fresh master seed and IV. + let database = + parse(&fixture("test_db_kdbx4_with_password_aes.kdbx"), "demopass").expect("read fixture"); + let (first, cache) = + write_model_cached(&database, "demopass", None).expect("first cached write"); + let (second, _cache) = + write_model_cached(&database, "demopass", Some(&cache)).expect("second cached write"); + assert_ne!(first, second, "master seed/IV must still be fresh"); + + let credentials = Credentials::password("demopass"); + let first_file = read_kdbx_bytes(&first, &credentials).expect("read first"); + let second_file = read_kdbx_bytes(&second, &credentials).expect("read second"); + assert_eq!(first_file.kdf.seed(), second_file.kdf.seed()); + assert!(parse(&second, "demopass").is_ok()); + + verify_written_with_cache(&second, "demopass", &cache).expect("verify cached save"); + let mut damaged = second.clone(); + let last = damaged.len() - 1; + damaged[last] ^= 0xff; + assert!(verify_written_with_cache(&damaged, "demopass", &cache).is_err()); +} diff --git a/crates/ffi/src/abi.rs b/crates/ffi/src/abi.rs new file mode 100644 index 0000000..2bcee36 --- /dev/null +++ b/crates/ffi/src/abi.rs @@ -0,0 +1,451 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! The C ABI surface: every extern C entry point. +//! Symbol names and signatures are the contract and must not change. + +use super::*; + +/// Returns the FFI main version. +#[no_mangle] +pub extern "C" fn kp_api_version() -> u32 { + API_MAJOR +} + +/// Borrowed last-error JSON (valid until the next call on this thread). +#[no_mangle] +pub extern "C" fn kp_last_error_json() -> *const c_char { + LAST_ERROR.with(|slot| { + slot.borrow() + .as_ref() + .map_or(std::ptr::null(), |error| error.as_ptr()) + }) +} + +/// Free a `char*` returned by this library. +#[no_mangle] +pub extern "C" fn kp_string_free(pointer: *mut c_char) { + if pointer.is_null() { + return; + } + unsafe { + drop(CString::from_raw(pointer)); + } +} + +/// Free a byte buffer returned by this library. +#[no_mangle] +pub extern "C" fn kp_buffer_free(pointer: *mut u8, len: usize) { + if pointer.is_null() { + return; + } + unsafe { + let slice = std::ptr::slice_from_raw_parts_mut(pointer, len); + drop(Box::from_raw(slice)); + } +} + +/// Open a KDBX byte buffer; `opts_json` must contain `{"password":"..."}`. +#[no_mangle] +pub extern "C" fn kp_open(kdbx: *const u8, len: usize, opts_json: *const c_char) -> *mut KpHandle { + match catch_unwind(AssertUnwindSafe(|| { + if kdbx.is_null() { + return Err(FfiError::invalid("KDBX buffer is null")); + } + let bytes = unsafe { std::slice::from_raw_parts(kdbx, len) }; + let password = options_password(opts_json)?; + let database = open_database(bytes, &password)?; + clear_last_error(); + Ok(Box::into_raw(Box::new(KpHandle { + state: Mutex::new(HandleState { + database: Some(database), + password: Some(password), + kdf_cache: None, + dirty: false, + baseline: SyncBaseline::default(), + last_sync_unix: None, + subscriber: None, + }), + }))) + })) { + Ok(Ok(handle)) => handle, + Ok(Err(error)) => { + fail(error); + std::ptr::null_mut() + } + Err(_) => { + fail(FfiError::internal("panic in kp_open")); + std::ptr::null_mut() + } + } +} + +/// Lock and clear the decrypted database. +#[no_mangle] +pub extern "C" fn kp_lock(handle: *mut KpHandle) -> i32 { + guarded(|| { + match with_state(handle, |state| { + state.database = None; + state.password = None; + state.kdf_cache = None; + Ok(()) + }) { + Ok(()) => success(), + Err(error) => fail(error), + } + }) +} + +/// Close a handle and free its resources. +#[no_mangle] +pub extern "C" fn kp_close(handle: *mut KpHandle) -> i32 { + guarded(|| { + if handle.is_null() { + return fail(FfiError::invalid("handle is null")); + } + unsafe { + drop(Box::from_raw(handle)); + } + success() + }) +} + +/// Invoke one JSON command (`{"command":"...", ...}`). +#[no_mangle] +pub extern "C" fn kp_call( + handle: *mut KpHandle, + cmd_json: *const c_char, + out_json: *mut *mut c_char, +) -> i32 { + guarded(|| { + if cmd_json.is_null() || out_json.is_null() { + return fail(FfiError::invalid("command or output pointer is null")); + } + let text = match unsafe { CStr::from_ptr(cmd_json) }.to_str() { + Ok(text) => text, + Err(_) => return fail(FfiError::invalid("command JSON is not UTF-8")), + }; + let command: Value = match serde_json::from_str(text) { + Ok(command) => command, + Err(_) => return fail(FfiError::invalid("command JSON is invalid")), + }; + match with_state(handle, |state| dispatch(state, &command)) { + Ok(json_text) => match CString::new(json_text) { + Ok(value) => { + unsafe { + *out_json = value.into_raw(); + } + success() + } + Err(_) => fail(FfiError::internal("result contains NUL")), + }, + Err(error) => fail(error), + } + }) +} + +/// Save the current model as KDBX bytes. +#[no_mangle] +pub extern "C" fn kp_save( + handle: *mut KpHandle, + out_bytes: *mut *mut u8, + out_len: *mut usize, +) -> i32 { + guarded(|| { + if out_bytes.is_null() || out_len.is_null() { + return fail(FfiError::invalid("output pointers are null")); + } + match with_state(handle, |state| { + let password = state.password.clone().ok_or_else(FfiError::locked)?; + let cache = state.kdf_cache.take(); + let database = state.database.as_ref().ok_or_else(FfiError::locked)?; + let (bytes, cache) = writer::write_model_cached(database, &password, cache.as_ref()) + .map_err(|_| FfiError::new("IoError", "cannot serialize the database"))?; + // Verify the ciphertext before the caller can write it. The cache + // makes this a decrypt/parse, not a second KDF run. + writer::verify_written_with_cache(&bytes, &password, &cache) + .map_err(|_| FfiError::new("IoError", "the saved database failed verification"))?; + state.kdf_cache = Some(cache); + set_buffer(out_bytes, out_len, bytes); + Ok(()) + }) { + Ok(()) => success(), + Err(error) => fail(error), + } + }) +} + +pub(crate) fn set_buffer(out_bytes: *mut *mut u8, out_len: *mut usize, bytes: Vec) { + let len = bytes.len(); + let boxed: Box<[u8]> = bytes.into_boxed_slice(); + let pointer = Box::into_raw(boxed) as *mut u8; + unsafe { + *out_bytes = pointer; + *out_len = len; + } +} + +/// Validate that bytes decrypt to a KDBX database (no handle retained). +#[no_mangle] +pub extern "C" fn kp_verify(bytes: *const u8, len: usize, opts_json: *const c_char) -> i32 { + guarded(|| { + if bytes.is_null() { + return fail(FfiError::invalid("KDBX buffer is null")); + } + let slice = unsafe { std::slice::from_raw_parts(bytes, len) }; + match options_password(opts_json).and_then(|password| open_database(slice, &password)) { + Ok(_) => success(), + Err(error) => fail(error), + } + }) +} + +/// Create a new empty KDBX 4.0 database. `opts_json` is +/// `{"password":"...","name":"...","preset":"keepass-classic|keepassxc|desktop|strong"}` +/// or `{"password":"...","name":"...","kdf":{"type":"argon2id","memory_mib":64, +/// "iterations":3,"parallelism":2}}`; without either KDF field the backend +/// default applies. Output is a caller-owned byte buffer. +#[no_mangle] +pub extern "C" fn kp_create_database( + opts_json: *const c_char, + out_bytes: *mut *mut u8, + out_len: *mut usize, +) -> i32 { + guarded(|| { + if opts_json.is_null() || out_bytes.is_null() || out_len.is_null() { + return fail(FfiError::invalid("options or output pointer is null")); + } + let text = match unsafe { CStr::from_ptr(opts_json) }.to_str() { + Ok(text) => text, + Err(_) => return fail(FfiError::invalid("options JSON is not UTF-8")), + }; + let options: Value = match serde_json::from_str(text) { + Ok(value) => value, + Err(_) => return fail(FfiError::invalid("options JSON is invalid")), + }; + let password = match options.get("password").and_then(Value::as_str) { + Some(value) if !value.is_empty() => value, + _ => return fail(FfiError::invalid("password is required")), + }; + let name = options + .get("name") + .and_then(Value::as_str) + .unwrap_or("keepassity"); + let kdf = if options.get("preset").is_some() || options.get("kdf").is_some() { + match kdf_from_command(&options) { + Ok(kdf) => Some(kdf), + Err(error) => return fail(error), + } + } else { + None + }; + match keepassity_core::kdbx::writer::create_empty_with_kdf(name, password, kdf) { + Ok(bytes) => { + set_buffer(out_bytes, out_len, bytes); + success() + } + Err(_) => fail(FfiError::new("IoError", "cannot create database")), + } + }) +} + +/// Decide the next sync action from remote metadata. +#[no_mangle] +pub extern "C" fn kp_sync_decide( + handle: *mut KpHandle, + remote_meta_json: *const c_char, + local_dirty: i32, + out_json: *mut *mut c_char, +) -> i32 { + guarded(|| { + if remote_meta_json.is_null() || out_json.is_null() { + return fail(FfiError::invalid("metadata or output pointer is null")); + } + let text = match unsafe { CStr::from_ptr(remote_meta_json) }.to_str() { + Ok(text) => text, + Err(_) => return fail(FfiError::invalid("metadata JSON is not UTF-8")), + }; + let remote: SyncRemoteMeta = match serde_json::from_str(text) { + Ok(remote) => remote, + Err(_) => return fail(FfiError::invalid("metadata JSON is invalid")), + }; + match with_state(handle, |state| { + state.dirty = local_dirty != 0; + let mut sync_state = SyncState::new(state.baseline.clone()); + sync_state.local_dirty = state.dirty; + let decision = sync_state.decide(&keepassity_core::sync::RemoteMeta { + etag: remote.etag, + size: remote.size, + modified_unix: remote.modified_unix, + sha256: None, + }); + Ok(json!({ + "action": action_name(decision.action), + "reason": decision.reason, + "degraded": decision.degraded, + "retry_after_ms": decision.retry_after_ms, + }) + .to_string()) + }) { + Ok(text) => match CString::new(text) { + Ok(value) => { + unsafe { + *out_json = value.into_raw(); + } + success() + } + Err(_) => fail(FfiError::internal("NUL in JSON")), + }, + Err(error) => fail(error), + } + }) +} + +/// Download remote bytes, merge, write the merged result and return conflicts. +#[no_mangle] +pub extern "C" fn kp_sync_merge( + handle: *mut KpHandle, + remote: *const u8, + len: usize, + out_bytes: *mut *mut u8, + out_len: *mut usize, + conflicts_json: *mut *mut c_char, +) -> i32 { + guarded(|| { + if remote.is_null() || out_bytes.is_null() || out_len.is_null() || conflicts_json.is_null() + { + return fail(FfiError::invalid("argument pointer is null")); + } + let remote_bytes = unsafe { std::slice::from_raw_parts(remote, len) }; + match with_state(handle, |state| { + let password = state.password.clone().ok_or_else(FfiError::locked)?; + let remote_db = open_database(remote_bytes, &password)?; + let merged = { + let local = state.database.as_ref().ok_or_else(FfiError::locked)?; + merge_for_sync(local, &remote_db) + }; + let cache = state.kdf_cache.take(); + let (bytes, cache) = + writer::write_model_cached(&merged.database, &password, cache.as_ref()) + .map_err(|_| FfiError::new("IoError", "cannot serialize merged database"))?; + writer::verify_written_with_cache(&bytes, &password, &cache) + .map_err(|_| FfiError::new("IoError", "the merged database failed verification"))?; + let conflicts: Vec = + merged.conflicts.iter().map(ConflictItem::from).collect(); + let conflicts_text = serde_json::to_string(&conflicts) + .map_err(|_| FfiError::internal("cannot serialize conflicts"))?; + state.database = Some(merged.database); + state.kdf_cache = Some(cache); + state.dirty = true; + set_buffer(out_bytes, out_len, bytes); + unsafe { + *conflicts_json = CString::new(conflicts_text) + .map_err(|_| FfiError::internal("NUL in conflicts JSON"))? + .into_raw(); + } + Ok(()) + }) { + Ok(()) => success(), + Err(error) => fail(error), + } + }) +} + +/// Record a successful sync baseline. +#[no_mangle] +pub extern "C" fn kp_sync_commit( + handle: *mut KpHandle, + etag: *const c_char, + content_sha256: *const c_char, +) -> i32 { + guarded(|| { + let result = (|| { + let etag = c_string_opt(etag)?.filter(|value| !value.trim().is_empty()); + // A baseline without the content hash is not a baseline: the next + // sync could not tell whether the remote or local copy changed and + // would be free to overwrite the local database. Fail closed. + let sha = c_string_opt(content_sha256)? + .filter(|value| !value.trim().is_empty()) + .ok_or_else(|| { + FfiError::invalid("content SHA-256 is required for a sync baseline") + })?; + if sha.len() != 64 || !sha.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(FfiError::invalid( + "content SHA-256 must be 64 hexadecimal characters", + )); + } + with_state(handle, |state| { + state.baseline = SyncBaseline { + etag, + sha256: Some(sha), + size: None, + modified_unix: None, + }; + state.dirty = false; + state.last_sync_unix = Some(now_unix()); + Ok(()) + }) + })(); + match result { + Ok(()) => success(), + Err(error) => fail(error), + } + }) +} + +/// Mark local state dirty (unsaved/unuploaded edits). +#[no_mangle] +pub extern "C" fn kp_sync_mark_dirty(handle: *mut KpHandle) -> i32 { + guarded(|| { + match with_state(handle, |state| { + state.dirty = true; + Ok(()) + }) { + Ok(()) => success(), + Err(error) => fail(error), + } + }) +} + +/// Subscribe to events (v1 stores the callback; close/unsubscribe first). +#[no_mangle] +pub extern "C" fn kp_subscribe( + handle: *mut KpHandle, + callback: KpEventCb, + user: *mut c_void, +) -> i32 { + guarded(|| { + match with_state(handle, |state| { + state.subscriber = Some(Subscriber { + _callback: callback, + _user: user, + }); + Ok(()) + }) { + Ok(()) => success(), + Err(error) => fail(error), + } + }) +} + +/// Remove the event subscription. +#[no_mangle] +pub extern "C" fn kp_unsubscribe(handle: *mut KpHandle) -> i32 { + guarded(|| { + match with_state(handle, |state| { + state.subscriber = None; + Ok(()) + }) { + Ok(()) => success(), + Err(error) => fail(error), + } + }) +} + +pub(crate) fn c_string_opt(pointer: *const c_char) -> Result, FfiError> { + if pointer.is_null() { + return Ok(None); + } + unsafe { CStr::from_ptr(pointer) } + .to_str() + .map(|text| Some(text.to_string())) + .map_err(|_| FfiError::invalid("argument is not UTF-8")) +} diff --git a/crates/ffi/src/dispatch.rs b/crates/ffi/src/dispatch.rs new file mode 100644 index 0000000..25841a0 --- /dev/null +++ b/crates/ffi/src/dispatch.rs @@ -0,0 +1,379 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Command dispatch: one JSON command in, one JSON result out. + +use super::*; + +pub(crate) fn dispatch(state: &mut HandleState, command: &Value) -> Result { + let name = command + .get("command") + .or_else(|| command.get("cmd")) + .and_then(Value::as_str) + .ok_or_else(|| FfiError::invalid("command name is required"))?; + match name { + "version" => Ok(json!({ + "api": API_MAJOR, + "core_version": keepassity_core::version(), + "write_kdbx_version": writer::DEFAULT_WRITE_VERSION, + }) + .to_string()), + "list_groups" => with_database(state, |database| { + Ok(json!(flatten_groups(database)).to_string()) + }), + "create_group" => with_database_dirty(state, |database| { + let parent_uuid = parse_uuid_arg(command, "parent_uuid")?; + let name = parse_group_name(command)?; + let parent = find_group_mut(database, parent_uuid).ok_or_else(FfiError::not_found)?; + let uuid = new_uuid(); + let now = now_unix(); + let stamp = xml_datetime_from_unix(now); + let group = Group { + uuid, + name, + icon_id: 48, + times: Times { + creation: stamp.clone(), + last_modification: stamp.clone(), + last_access: stamp.clone(), + expiry: stamp.clone(), + location_changed: stamp, + ..Times::default() + }, + is_expanded: true, + ..Group::default() + }; + parent.groups.push(group); + Ok(json!({"uuid": uuid.to_hex()}).to_string()) + }), + "rename_group" => with_database_dirty(state, |database| { + let uuid = parse_uuid_arg(command, "uuid")?; + let name = parse_group_name(command)?; + let group = find_group_mut(database, uuid).ok_or_else(FfiError::not_found)?; + group.name = name; + group.times.last_modification = xml_datetime_from_unix(now_unix()); + Ok(json!({"uuid": uuid.to_hex()}).to_string()) + }), + "delete_group" => with_database_dirty(state, |database| { + let uuid = parse_uuid_arg(command, "uuid")?; + if uuid == database.root.uuid { + return Err(FfiError::invalid("the root group cannot be deleted")); + } + if database.meta.recycle_bin_uuid == Some(uuid) { + return Err(FfiError::invalid("the recycle bin group cannot be deleted")); + } + let permanent = command + .get("permanent") + .and_then(Value::as_bool) + .unwrap_or(false); + + // A group is recycled like an entry: move the whole subtree under + // the recycle bin instead of destroying it. If the recycle bin is + // disabled (or would end up inside the removed subtree), fall back + // to a permanent delete with tombstones so a remote merge does not + // resurrect the group. + let recycle_target = if permanent { + None + } else { + ensure_recycle_bin(database) + }; + let can_recycle = recycle_target.is_some_and(|target| { + find_group(database, uuid).is_some_and(|group| !group_contains_uuid(group, target)) + }); + let mut tombstones = Vec::new(); + if !can_recycle { + let group = find_group(database, uuid).ok_or_else(FfiError::not_found)?; + collect_group_tombstones(group, &mut tombstones); + } + let mut removed = + remove_group(&mut database.root, uuid).ok_or_else(FfiError::not_found)?; + let recycled = can_recycle && recycle_target.is_some(); + if recycled { + let target = recycle_target.expect("checked above"); + removed.times.location_changed = xml_datetime_from_unix(now_unix()); + find_group_mut(database, target) + .expect("recycle bin checked above") + .groups + .push(removed); + } else { + let deletion_time = xml_datetime_from_unix(now_unix()); + for deleted_uuid in tombstones { + database.deleted_objects.push(DeletedObject { + uuid: deleted_uuid, + deletion_time: deletion_time.clone(), + }); + } + } + Ok(json!({"deleted": true, "recycled": recycled}).to_string()) + }), + "list_entries" => with_database(state, |database| { + let entries = select_entries( + database, + command.get("group_uuid").and_then(Value::as_str), + command + .get("include_subgroups") + .and_then(Value::as_bool) + .unwrap_or(true), + ); + let summaries: Vec = entries + .into_iter() + .map(|(entry, group)| EntrySummary::from_model(entry, group)) + .collect(); + Ok(json!(summaries).to_string()) + }), + "get_entry" => with_database(state, |database| { + let uuid = parse_uuid_arg(command, "uuid")?; + let (entry, parent) = find_entry(database, uuid).ok_or_else(FfiError::not_found)?; + let mut full = EntryFull::from_model(entry, parent); + if let Ok(Some(read)) = totp_fields::read_entry(entry) { + full.totp = Some(core_totp_to_dto(&read.spec)); + } + Ok(json!(full).to_string()) + }), + "search" => with_database(state, |database| { + let query = command + .get("query") + .and_then(Value::as_str) + .ok_or_else(|| FfiError::invalid("query is required"))? + .to_lowercase(); + let limit = command + .get("limit") + .and_then(Value::as_u64) + .unwrap_or(100) + .min(1_000) as usize; + let fields = command + .get("fields") + .and_then(Value::as_array) + .map(|values| values.iter().filter_map(Value::as_str).collect::>()) + .unwrap_or_else(|| vec!["Title", "UserName", "URL", "Notes"]); + let mut matches = Vec::new(); + for (entry, parent) in all_entries(database) { + let mut matched = Vec::new(); + for field in &fields { + if entry + .field(field) + .is_some_and(|value| value.to_lowercase().contains(&query)) + { + matched.push((*field).to_string()); + } + } + if !matched.is_empty() { + matches.push(json!({ + "entry": EntrySummary::from_model(entry, parent), + "matched_fields": matched, + })); + if matches.len() >= limit { + break; + } + } + } + Ok(json!({"matches": matches}).to_string()) + }), + "create_entry" => with_database_dirty(state, |database| { + let group_uuid = parse_uuid_arg(command, "group_uuid")?; + let fields = command + .get("fields") + .and_then(Value::as_object) + .ok_or_else(|| FfiError::invalid("fields object is required"))?; + let group = find_group_mut(database, group_uuid).ok_or_else(FfiError::not_found)?; + let uuid = new_uuid(); + let entry = entry_from_fields(uuid, fields); + group.entries.push(entry); + Ok(json!({"uuid": uuid.to_hex()}).to_string()) + }), + "update_entry" => with_database_dirty(state, |database| { + let uuid = parse_uuid_arg(command, "uuid")?; + let patch = command + .get("patch") + .and_then(Value::as_object) + .ok_or_else(|| FfiError::invalid("patch object is required"))?; + let limits = HistoryLimits::from_meta(&database.meta); + let (entry, _) = find_entry_mut(database, uuid).ok_or_else(FfiError::not_found)?; + // Keep the previous version recoverable before changing anything; + // KeePass expects history to grow on every edit, bounded by the + // database's own retention settings. + entry.push_history_snapshot(limits); + apply_patch(entry, patch); + let now = now_unix(); + touch(entry, now); + Ok(json!({"uuid": uuid.to_hex(), "modified_unix": now}).to_string()) + }), + "delete_entry" => with_database_dirty(state, |database| { + let uuid = parse_uuid_arg(command, "uuid")?; + let permanent = command + .get("permanent") + .and_then(Value::as_bool) + .unwrap_or(false); + let (mut entry, _) = + remove_entry(&mut database.root, uuid).ok_or_else(FfiError::not_found)?; + let mut recycled = false; + if !permanent { + if let Some(target) = ensure_recycle_bin(database) { + if let Some(group) = find_group_mut(database, target) { + entry.times.location_changed = xml_datetime_from_unix(now_unix()); + group.entries.push(entry); + recycled = true; + } + } + } + if !recycled { + database.deleted_objects.push(DeletedObject { + uuid, + deletion_time: xml_datetime_from_unix(now_unix()), + }); + } + Ok(json!({"deleted": true, "recycled": recycled}).to_string()) + }), + "move_entry" => with_database_dirty(state, |database| { + let uuid = parse_uuid_arg(command, "uuid")?; + let target = parse_uuid_arg(command, "group_uuid")?; + // Validate the destination before removing the entry: a failed + // move must leave the in-memory model unchanged. + if find_group(database, target).is_none() { + return Err(FfiError::not_found()); + } + let (mut entry, old_parent) = + remove_entry(&mut database.root, uuid).ok_or_else(FfiError::not_found)?; + let target_group = find_group_mut(database, target).ok_or_else(FfiError::not_found)?; + entry.previous_parent_group = Some(old_parent); + entry.times.location_changed = xml_datetime_from_unix(now_unix()); + target_group.entries.push(entry); + Ok(json!({"moved": true}).to_string()) + }), + "totp_code" => with_database(state, |database| { + let uuid = parse_uuid_arg(command, "uuid")?; + let at = command + .get("at_unix") + .and_then(Value::as_u64) + .unwrap_or_else(|| now_unix() as u64); + let (entry, _) = find_entry(database, uuid).ok_or_else(FfiError::not_found)?; + let read = totp_fields::read_entry(entry) + .map_err(|error| FfiError::invalid(error.to_string()))? + .ok_or_else(|| FfiError::new("NotFound", "entry has no TOTP configuration"))?; + let code = generate_at(&read.spec.config, at) + .map_err(|error| FfiError::invalid(error.to_string()))?; + let spec = read.spec; + Ok(json!({ + "code": code.code, + "remaining": code.remaining, + "period": code.period, + "digits": code.digits, + "algorithm": algorithm_name(code.algorithm), + "issuer": spec.issuer, + "account": spec.account, + "skew_warning": false, + }) + .to_string()) + }), + "totp_parse_uri" => { + let uri = command + .get("uri") + .and_then(Value::as_str) + .ok_or_else(|| FfiError::invalid("uri is required"))?; + let spec = totp_fields::parse_uri(uri) + .map_err(|error| FfiError::invalid(error.to_string()))?; + Ok(json!(core_totp_to_dto(&spec)).to_string()) + } + "totp_set" => with_database_dirty(state, |database| { + let uuid = parse_uuid_arg(command, "uuid")?; + let config = command + .get("config") + .ok_or_else(|| FfiError::invalid("config is required"))?; + let spec = dto_to_totp_spec(config)?; + let (entry, _) = find_entry_mut(database, uuid).ok_or_else(FfiError::not_found)?; + let update = totp_fields::dual_write(&spec) + .map_err(|error| FfiError::invalid(error.to_string()))?; + for key in &update.remove { + entry.strings.retain(|field| &field.key != key); + } + for field in update.set { + set_field(entry, &field.key, &field.value, field.protected); + } + Ok(json!({"ok": true}).to_string()) + }), + "totp_delete" => with_database_dirty(state, |database| { + let uuid = parse_uuid_arg(command, "uuid")?; + let (entry, _) = find_entry_mut(database, uuid).ok_or_else(FfiError::not_found)?; + entry.strings.retain(|field| { + field.key != "otp" + && field.key != "TOTP Seed" + && field.key != "TOTP Settings" + && !field.key.starts_with("TimeOtp-") + }); + Ok(json!({"ok": true}).to_string()) + }), + "password_generate" => { + let length = command + .get("length") + .and_then(Value::as_u64) + .unwrap_or(20) + .clamp(1, 256) as usize; + let classes = command.get("classes"); + let exclude_ambiguous = command + .get("exclude_ambiguous") + .and_then(Value::as_bool) + .unwrap_or(true); + let (password, entropy_bits) = generate_password(length, classes, exclude_ambiguous)?; + Ok(json!({"password": password, "entropy_bits": entropy_bits}).to_string()) + } + "sync_state" => Ok(json!({ + "dirty": state.dirty, + "last_sync_unix": state.last_sync_unix, + "baseline_present": state.baseline.etag.is_some() || state.baseline.sha256.is_some(), + }) + .to_string()), + "export_model_json" => with_database(state, |database| { + let dump = database + .canonical_json() + .map_err(|error| FfiError::internal(error.to_string()))?; + let sha = local_hash(dump.as_bytes()); + Ok(json!({"model": dump, "sha256": sha}).to_string()) + }), + "diagnose" => with_database(state, |database| { + let (groups, entries, totp_entries, history) = database_stats(database); + Ok(json!({ + "format_version": database.format_version.clone(), + "groups": groups, + "entries": entries, + "totp_entries": totp_entries, + "history_entries": history, + "write_backend": writer::WRITE_BACKEND, + "kdf": database.outer.as_ref().and_then(|header| header.kdf.as_ref()).map(kdf_json), + }) + .to_string()) + }), + // Read-only view of the encryption parameters the file carries. The app + // shows them verbatim; it never derives its own opinion from them. + "database_info" => with_database(state, |database| Ok(kdf_info_json(database))), + // Explicit, user-initiated KDF change. The cached transformed key belongs + // to the previous parameters and must not survive. + "set_kdf" => { + let wanted = kdf_from_command(command)?; + let info = with_database_dirty(state, |database| { + database + .set_kdf(wanted) + .map_err(|error| FfiError::invalid(error.to_string()))?; + Ok(kdf_info_json(database)) + })?; + state.kdf_cache = None; + Ok(info) + } + // KDBX built-in settings (Meta) shown on the database settings page. + // Changing them marks the model dirty; they reach the file on the next save. + "database_settings" => { + with_database(state, |database| Ok(database_settings_json(database))) + } + "set_database_settings" => { + let (recycle, history) = parse_database_settings(command)?; + let info = with_database_dirty(state, |database| { + if let Some(enabled) = recycle { + database.meta.recycle_bin_enabled = enabled; + } + if let Some(items) = history { + database.meta.history_max_items = items; + } + Ok(database_settings_json(database)) + })?; + Ok(info) + } + other => Err(FfiError::invalid(format!("unknown command: {other}"))), + } +} diff --git a/crates/ffi/src/json_helpers.rs b/crates/ffi/src/json_helpers.rs new file mode 100644 index 0000000..dca541d --- /dev/null +++ b/crates/ffi/src/json_helpers.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! JSON projections: KDF and outer-header facts, database settings and stats. + +use super::*; + +pub(crate) fn parse_group_name(command: &Value) -> Result { + let name = command + .get("name") + .and_then(Value::as_str) + .map(str::trim) + .filter(|name| !name.is_empty()) + .ok_or_else(|| FfiError::invalid("group name is required"))?; + Ok(name.to_string()) +} + +pub(crate) fn kdf_info_json(database: &Database) -> String { + let header = database.outer.as_ref(); + json!({ + "format_version": database.format_version.clone(), + // The root group UUID is the stable identity of a KDBX database; the + // format has no database-level UUID. + "vault_uuid": database.root.uuid.to_string(), + "name": database.meta.database_name.clone(), + "cipher": header.map(|header| cipher_name(&header.cipher)), + "compression": header.map(|header| compression_name(&header.compression)), + "kdf": header.and_then(|header| header.kdf.as_ref()).map(kdf_json), + }) + .to_string() +} + +pub(crate) fn database_settings_json(database: &Database) -> String { + json!({ + "recycle_bin_enabled": database.meta.recycle_bin_enabled, + "history_max_items": database.meta.history_max_items, + "history_max_size": database.meta.history_max_size, + }) + .to_string() +} + +/// Fields of `set_database_settings`; unset fields stay as they are. +pub(crate) fn parse_database_settings( + command: &Value, +) -> Result<(Option, Option), FfiError> { + let recycle = command.get("recycle_bin_enabled").and_then(Value::as_bool); + let history = command.get("history_max_items").and_then(Value::as_i64); + if let Some(items) = history { + if !(0..=10_000).contains(&items) { + return Err(FfiError::invalid( + "history_max_items must be between 0 and 10000", + )); + } + } + if recycle.is_none() && history.is_none() { + return Err(FfiError::invalid( + "set_database_settings needs recycle_bin_enabled or history_max_items", + )); + } + Ok((recycle, history)) +} + +pub(crate) fn kdf_json(kdf: &KdfSettings) -> Value { + match kdf { + KdfSettings::Aes { rounds } => json!({ + "type": "aes-kdf", + "rounds": rounds, + "mobile_safe": kdf.is_mobile_safe(), + }), + KdfSettings::Argon2 { + kind, + iterations, + memory_kib, + parallelism, + version, + } => json!({ + "type": match kind { + Argon2Kind::D => "argon2d", + Argon2Kind::Id => "argon2id", + }, + "memory_kib": memory_kib, + "memory_mib": memory_kib / 1024, + "iterations": iterations, + "parallelism": parallelism, + "version": version, + "mobile_safe": kdf.is_mobile_safe(), + }), + } +} + +pub(crate) fn cipher_name(cipher: &OuterCipher) -> &'static str { + match cipher { + OuterCipher::Aes128 => "aes128", + OuterCipher::Aes256 => "aes256", + OuterCipher::Twofish => "twofish", + OuterCipher::ChaCha20 => "chacha20", + } +} + +pub(crate) fn compression_name(compression: &OuterCompression) -> &'static str { + match compression { + OuterCompression::None => "none", + OuterCompression::Gzip => "gzip", + } +} + +/// Parse `{"preset": "..."}` or `{"kdf": {...}}` into KDF settings. +/// +/// Validation happens in `Database::set_kdf`, so a custom object that exceeds +/// the reader limits is rejected before anything is written. +pub(crate) fn kdf_from_command(command: &Value) -> Result { + if let Some(preset) = command.get("preset").and_then(Value::as_str) { + return match preset { + "keepass-classic" | "aes-600k" => Ok(KdfPreset::KeepassClassic.settings()), + "keepassxc" | "mobile" => Ok(KdfPreset::KeepassXc.settings()), + "desktop" => Ok(KdfPreset::Desktop.settings()), + "strong" => Ok(KdfPreset::Strong.settings()), + other => Err(FfiError::invalid(format!("unknown KDF preset: {other}"))), + }; + } + let kdf = command + .get("kdf") + .ok_or_else(|| FfiError::invalid("set_kdf needs a preset or a kdf object"))?; + let kind = kdf + .get("type") + .and_then(Value::as_str) + .unwrap_or("argon2id"); + match kind { + "aes-kdf" | "aes" => Ok(KdfSettings::Aes { + rounds: kdf.get("rounds").and_then(Value::as_u64).unwrap_or(600_000), + }), + "argon2d" | "argon2id" => { + let memory_mib = kdf.get("memory_mib").and_then(Value::as_u64).unwrap_or(64); + let memory_kib = memory_mib.saturating_mul(1024); + Ok(KdfSettings::Argon2 { + kind: if kind == "argon2d" { + Argon2Kind::D + } else { + Argon2Kind::Id + }, + iterations: u32::try_from( + kdf.get("iterations").and_then(Value::as_u64).unwrap_or(3), + ) + .unwrap_or(u32::MAX), + memory_kib: u32::try_from(memory_kib).unwrap_or(u32::MAX), + parallelism: u32::try_from( + kdf.get("parallelism").and_then(Value::as_u64).unwrap_or(2), + ) + .unwrap_or(u32::MAX), + version: 0x13, + }) + } + other => Err(FfiError::invalid(format!("unknown KDF type: {other}"))), + } +} + +pub(crate) fn database_stats(database: &Database) -> (usize, usize, usize, usize) { + fn walk(group: &Group, counts: &mut (usize, usize, usize, usize)) { + counts.0 += 1; + for entry in &group.entries { + counts.1 += 1; + counts.3 += entry.history.len(); + if entry.has_totp() { + counts.2 += 1; + } + } + for child in &group.groups { + walk(child, counts); + } + } + let mut counts = (0, 0, 0, 0); + walk(&database.root, &mut counts); + counts +} diff --git a/crates/ffi/src/lib.rs b/crates/ffi/src/lib.rs index f057f8d..2f5ffde 100644 --- a/crates/ffi/src/lib.rs +++ b/crates/ffi/src/lib.rs @@ -14,7 +14,8 @@ use keepassity_core::dto::{ }; use keepassity_core::kdbx::writer; use keepassity_core::model::{ - xml_datetime_from_unix, Database, DeletedObject, Entry, Group, StringField, Times, Uuid, + xml_datetime_from_unix, Argon2Kind, Database, DeletedObject, Entry, Group, HistoryLimits, + KdfPreset, KdfSettings, OuterCipher, OuterCompression, StringField, Times, Uuid, }; use keepassity_core::sync::{local_hash, merge_for_sync, SyncActionKind, SyncBaseline, SyncState}; use keepassity_core::totp::fields as totp_fields; @@ -43,6 +44,8 @@ struct Subscriber { struct HandleState { database: Option, password: Option, + /// Transformed KDF key for the next save. Dropped on lock/close. + kdf_cache: Option, dirty: bool, baseline: SyncBaseline, last_sync_unix: Option, @@ -130,45 +133,6 @@ fn guarded(function: impl FnOnce() -> i32) -> i32 { } } -/// Returns the FFI main version. -#[no_mangle] -pub extern "C" fn kp_api_version() -> u32 { - API_MAJOR -} - -/// Borrowed last-error JSON (valid until the next call on this thread). -#[no_mangle] -pub extern "C" fn kp_last_error_json() -> *const c_char { - LAST_ERROR.with(|slot| { - slot.borrow() - .as_ref() - .map_or(std::ptr::null(), |error| error.as_ptr()) - }) -} - -/// Free a `char*` returned by this library. -#[no_mangle] -pub extern "C" fn kp_string_free(pointer: *mut c_char) { - if pointer.is_null() { - return; - } - unsafe { - drop(CString::from_raw(pointer)); - } -} - -/// Free a byte buffer returned by this library. -#[no_mangle] -pub extern "C" fn kp_buffer_free(pointer: *mut u8, len: usize) { - if pointer.is_null() { - return; - } - unsafe { - let slice = std::ptr::slice_from_raw_parts_mut(pointer, len); - drop(Box::from_raw(slice)); - } -} - fn options_password(opts: *const c_char) -> Result { if opts.is_null() { return Err(FfiError::invalid("missing options JSON")); @@ -202,40 +166,6 @@ fn open_database(bytes: &[u8], password: &str) -> Result { }) } -/// Open a KDBX byte buffer; `opts_json` must contain `{"password":"..."}`. -#[no_mangle] -pub extern "C" fn kp_open(kdbx: *const u8, len: usize, opts_json: *const c_char) -> *mut KpHandle { - match catch_unwind(AssertUnwindSafe(|| { - if kdbx.is_null() { - return Err(FfiError::invalid("KDBX buffer is null")); - } - let bytes = unsafe { std::slice::from_raw_parts(kdbx, len) }; - let password = options_password(opts_json)?; - let database = open_database(bytes, &password)?; - clear_last_error(); - Ok(Box::into_raw(Box::new(KpHandle { - state: Mutex::new(HandleState { - database: Some(database), - password: Some(password), - dirty: false, - baseline: SyncBaseline::default(), - last_sync_unix: None, - subscriber: None, - }), - }))) - })) { - Ok(Ok(handle)) => handle, - Ok(Err(error)) => { - fail(error); - std::ptr::null_mut() - } - Err(_) => { - fail(FfiError::internal("panic in kp_open")); - std::ptr::null_mut() - } - } -} - fn with_state( handle: *mut KpHandle, function: impl FnOnce(&mut HandleState) -> Result, @@ -275,1438 +205,20 @@ fn with_database_dirty( Ok(result) } -/// Lock and clear the decrypted database. -#[no_mangle] -pub extern "C" fn kp_lock(handle: *mut KpHandle) -> i32 { - guarded(|| { - match with_state(handle, |state| { - state.database = None; - state.password = None; - Ok(()) - }) { - Ok(()) => success(), - Err(error) => fail(error), - } - }) -} - -/// Close a handle and free its resources. -#[no_mangle] -pub extern "C" fn kp_close(handle: *mut KpHandle) -> i32 { - guarded(|| { - if handle.is_null() { - return fail(FfiError::invalid("handle is null")); - } - unsafe { - drop(Box::from_raw(handle)); - } - success() - }) -} - -/// Invoke one JSON command (`{"command":"...", ...}`). -#[no_mangle] -pub extern "C" fn kp_call( - handle: *mut KpHandle, - cmd_json: *const c_char, - out_json: *mut *mut c_char, -) -> i32 { - guarded(|| { - if cmd_json.is_null() || out_json.is_null() { - return fail(FfiError::invalid("command or output pointer is null")); - } - let text = match unsafe { CStr::from_ptr(cmd_json) }.to_str() { - Ok(text) => text, - Err(_) => return fail(FfiError::invalid("command JSON is not UTF-8")), - }; - let command: Value = match serde_json::from_str(text) { - Ok(command) => command, - Err(_) => return fail(FfiError::invalid("command JSON is invalid")), - }; - match with_state(handle, |state| dispatch(state, &command)) { - Ok(json_text) => match CString::new(json_text) { - Ok(value) => { - unsafe { - *out_json = value.into_raw(); - } - success() - } - Err(_) => fail(FfiError::internal("result contains NUL")), - }, - Err(error) => fail(error), - } - }) -} - -fn dispatch(state: &mut HandleState, command: &Value) -> Result { - let name = command - .get("command") - .or_else(|| command.get("cmd")) - .and_then(Value::as_str) - .ok_or_else(|| FfiError::invalid("command name is required"))?; - match name { - "version" => Ok(json!({ - "api": API_MAJOR, - "core_version": keepassity_core::version(), - "write_kdbx_version": writer::DEFAULT_WRITE_VERSION, - }) - .to_string()), - "list_groups" => with_database(state, |database| { - Ok(json!(flatten_groups(database)).to_string()) - }), - "create_group" => with_database_dirty(state, |database| { - let parent_uuid = parse_uuid_arg(command, "parent_uuid")?; - let name = parse_group_name(command)?; - let parent = find_group_mut(database, parent_uuid).ok_or_else(FfiError::not_found)?; - let uuid = new_uuid(); - let now = now_unix(); - let stamp = xml_datetime_from_unix(now); - let group = Group { - uuid, - name, - icon_id: 48, - times: Times { - creation: stamp.clone(), - last_modification: stamp.clone(), - last_access: stamp.clone(), - expiry: stamp.clone(), - location_changed: stamp, - ..Times::default() - }, - is_expanded: true, - ..Group::default() - }; - parent.groups.push(group); - Ok(json!({"uuid": uuid.to_hex()}).to_string()) - }), - "rename_group" => with_database_dirty(state, |database| { - let uuid = parse_uuid_arg(command, "uuid")?; - let name = parse_group_name(command)?; - let group = find_group_mut(database, uuid).ok_or_else(FfiError::not_found)?; - group.name = name; - group.times.last_modification = xml_datetime_from_unix(now_unix()); - Ok(json!({"uuid": uuid.to_hex()}).to_string()) - }), - "delete_group" => with_database_dirty(state, |database| { - let uuid = parse_uuid_arg(command, "uuid")?; - if uuid == database.root.uuid { - return Err(FfiError::invalid("the root group cannot be deleted")); - } - if database.meta.recycle_bin_uuid == Some(uuid) { - return Err(FfiError::invalid("the recycle bin group cannot be deleted")); - } - let group = find_group(database, uuid).ok_or_else(FfiError::not_found)?; - let mut tombstones = Vec::new(); - collect_group_tombstones(group, &mut tombstones); - remove_group(&mut database.root, uuid).ok_or_else(FfiError::not_found)?; - - // Record the group and every removed descendant/entry. Without - // tombstones a later remote merge would resurrect the subtree. - let deletion_time = xml_datetime_from_unix(now_unix()); - for deleted_uuid in tombstones { - database.deleted_objects.push(DeletedObject { - uuid: deleted_uuid, - deletion_time: deletion_time.clone(), - }); - } - Ok(json!({"deleted": true}).to_string()) - }), - "list_entries" => with_database(state, |database| { - let entries = select_entries( - database, - command.get("group_uuid").and_then(Value::as_str), - command - .get("include_subgroups") - .and_then(Value::as_bool) - .unwrap_or(true), - ); - let summaries: Vec = entries - .into_iter() - .map(|(entry, group)| EntrySummary::from_model(entry, group)) - .collect(); - Ok(json!(summaries).to_string()) - }), - "get_entry" => with_database(state, |database| { - let uuid = parse_uuid_arg(command, "uuid")?; - let (entry, parent) = find_entry(database, uuid).ok_or_else(FfiError::not_found)?; - let mut full = EntryFull::from_model(entry, parent); - if let Ok(Some(read)) = totp_fields::read_entry(entry) { - full.totp = Some(core_totp_to_dto(&read.spec)); - } - Ok(json!(full).to_string()) - }), - "search" => with_database(state, |database| { - let query = command - .get("query") - .and_then(Value::as_str) - .ok_or_else(|| FfiError::invalid("query is required"))? - .to_lowercase(); - let limit = command - .get("limit") - .and_then(Value::as_u64) - .unwrap_or(100) - .min(1_000) as usize; - let fields = command - .get("fields") - .and_then(Value::as_array) - .map(|values| values.iter().filter_map(Value::as_str).collect::>()) - .unwrap_or_else(|| vec!["Title", "UserName", "URL", "Notes"]); - let mut matches = Vec::new(); - for (entry, parent) in all_entries(database) { - let mut matched = Vec::new(); - for field in &fields { - if entry - .field(field) - .is_some_and(|value| value.to_lowercase().contains(&query)) - { - matched.push((*field).to_string()); - } - } - if !matched.is_empty() { - matches.push(json!({ - "entry": EntrySummary::from_model(entry, parent), - "matched_fields": matched, - })); - if matches.len() >= limit { - break; - } - } - } - Ok(json!({"matches": matches}).to_string()) - }), - "create_entry" => with_database_dirty(state, |database| { - let group_uuid = parse_uuid_arg(command, "group_uuid")?; - let fields = command - .get("fields") - .and_then(Value::as_object) - .ok_or_else(|| FfiError::invalid("fields object is required"))?; - let group = find_group_mut(database, group_uuid).ok_or_else(FfiError::not_found)?; - let uuid = new_uuid(); - let entry = entry_from_fields(uuid, fields); - group.entries.push(entry); - Ok(json!({"uuid": uuid.to_hex()}).to_string()) - }), - "update_entry" => with_database_dirty(state, |database| { - let uuid = parse_uuid_arg(command, "uuid")?; - let patch = command - .get("patch") - .and_then(Value::as_object) - .ok_or_else(|| FfiError::invalid("patch object is required"))?; - let (entry, _) = find_entry_mut(database, uuid).ok_or_else(FfiError::not_found)?; - apply_patch(entry, patch); - let now = now_unix(); - touch(entry, now); - Ok(json!({"uuid": uuid.to_hex(), "modified_unix": now}).to_string()) - }), - "delete_entry" => with_database_dirty(state, |database| { - let uuid = parse_uuid_arg(command, "uuid")?; - let permanent = command - .get("permanent") - .and_then(Value::as_bool) - .unwrap_or(false); - let (entry, _) = - remove_entry(&mut database.root, uuid).ok_or_else(FfiError::not_found)?; - let recycle = database.meta.recycle_bin_enabled && !permanent; - let mut recycled = false; - if recycle { - if let Some(target) = database.meta.recycle_bin_uuid { - if let Some(group) = find_group_mut(database, target) { - group.entries.push(entry); - recycled = true; - } - } - } - if !recycled { - database.deleted_objects.push(DeletedObject { - uuid, - deletion_time: xml_datetime_from_unix(now_unix()), - }); - } - Ok(json!({"deleted": true}).to_string()) - }), - "move_entry" => with_database_dirty(state, |database| { - let uuid = parse_uuid_arg(command, "uuid")?; - let target = parse_uuid_arg(command, "group_uuid")?; - let (mut entry, old_parent) = - remove_entry(&mut database.root, uuid).ok_or_else(FfiError::not_found)?; - let target_group = find_group_mut(database, target).ok_or_else(FfiError::not_found)?; - entry.previous_parent_group = Some(old_parent); - entry.times.location_changed = xml_datetime_from_unix(now_unix()); - target_group.entries.push(entry); - Ok(json!({"moved": true}).to_string()) - }), - "totp_code" => with_database(state, |database| { - let uuid = parse_uuid_arg(command, "uuid")?; - let at = command - .get("at_unix") - .and_then(Value::as_u64) - .unwrap_or_else(|| now_unix() as u64); - let (entry, _) = find_entry(database, uuid).ok_or_else(FfiError::not_found)?; - let read = totp_fields::read_entry(entry) - .map_err(|error| FfiError::invalid(error.to_string()))? - .ok_or_else(|| FfiError::new("NotFound", "entry has no TOTP configuration"))?; - let code = generate_at(&read.spec.config, at) - .map_err(|error| FfiError::invalid(error.to_string()))?; - let spec = read.spec; - Ok(json!({ - "code": code.code, - "remaining": code.remaining, - "period": code.period, - "digits": code.digits, - "algorithm": algorithm_name(code.algorithm), - "issuer": spec.issuer, - "account": spec.account, - "skew_warning": false, - }) - .to_string()) - }), - "totp_parse_uri" => { - let uri = command - .get("uri") - .and_then(Value::as_str) - .ok_or_else(|| FfiError::invalid("uri is required"))?; - let spec = totp_fields::parse_uri(uri) - .map_err(|error| FfiError::invalid(error.to_string()))?; - Ok(json!(core_totp_to_dto(&spec)).to_string()) - } - "totp_set" => with_database_dirty(state, |database| { - let uuid = parse_uuid_arg(command, "uuid")?; - let config = command - .get("config") - .ok_or_else(|| FfiError::invalid("config is required"))?; - let spec = dto_to_totp_spec(config)?; - let (entry, _) = find_entry_mut(database, uuid).ok_or_else(FfiError::not_found)?; - let update = totp_fields::dual_write(&spec) - .map_err(|error| FfiError::invalid(error.to_string()))?; - for key in &update.remove { - entry.strings.retain(|field| &field.key != key); - } - for field in update.set { - set_field(entry, &field.key, &field.value, field.protected); - } - Ok(json!({"ok": true}).to_string()) - }), - "totp_delete" => with_database_dirty(state, |database| { - let uuid = parse_uuid_arg(command, "uuid")?; - let (entry, _) = find_entry_mut(database, uuid).ok_or_else(FfiError::not_found)?; - entry.strings.retain(|field| { - field.key != "otp" - && field.key != "TOTP Seed" - && field.key != "TOTP Settings" - && !field.key.starts_with("TimeOtp-") - }); - Ok(json!({"ok": true}).to_string()) - }), - "password_generate" => { - let length = command - .get("length") - .and_then(Value::as_u64) - .unwrap_or(20) - .clamp(1, 256) as usize; - let classes = command.get("classes"); - let exclude_ambiguous = command - .get("exclude_ambiguous") - .and_then(Value::as_bool) - .unwrap_or(true); - let (password, entropy_bits) = generate_password(length, classes, exclude_ambiguous)?; - Ok(json!({"password": password, "entropy_bits": entropy_bits}).to_string()) - } - "sync_state" => Ok(json!({ - "dirty": state.dirty, - "last_sync_unix": state.last_sync_unix, - "baseline_present": state.baseline.etag.is_some() || state.baseline.sha256.is_some(), - }) - .to_string()), - "export_model_json" => with_database(state, |database| { - let dump = database - .canonical_json() - .map_err(|error| FfiError::internal(error.to_string()))?; - let sha = local_hash(dump.as_bytes()); - Ok(json!({"model": dump, "sha256": sha}).to_string()) - }), - "diagnose" => with_database(state, |database| { - let (groups, entries, totp_entries, history) = database_stats(database); - Ok(json!({ - "format_version": database.format_version.clone(), - "groups": groups, - "entries": entries, - "totp_entries": totp_entries, - "history_entries": history, - "write_backend": writer::WRITE_BACKEND, - }) - .to_string()) - }), - other => Err(FfiError::invalid(format!("unknown command: {other}"))), - } -} - -/// Save the current model as KDBX bytes. -#[no_mangle] -pub extern "C" fn kp_save( - handle: *mut KpHandle, - out_bytes: *mut *mut u8, - out_len: *mut usize, -) -> i32 { - guarded(|| { - if out_bytes.is_null() || out_len.is_null() { - return fail(FfiError::invalid("output pointers are null")); - } - match with_state(handle, |state| { - let password = state.password.clone().ok_or_else(FfiError::locked)?; - let database = state.database.as_ref().ok_or_else(FfiError::locked)?; - let bytes = writer::write_model(database, &password) - .map_err(|_| FfiError::new("IoError", "cannot serialize the database"))?; - set_buffer(out_bytes, out_len, bytes); - Ok(()) - }) { - Ok(()) => success(), - Err(error) => fail(error), - } - }) -} - -fn set_buffer(out_bytes: *mut *mut u8, out_len: *mut usize, bytes: Vec) { - let len = bytes.len(); - let boxed: Box<[u8]> = bytes.into_boxed_slice(); - let pointer = Box::into_raw(boxed) as *mut u8; - unsafe { - *out_bytes = pointer; - *out_len = len; - } -} - -/// Validate that bytes decrypt to a KDBX database (no handle retained). -#[no_mangle] -pub extern "C" fn kp_verify(bytes: *const u8, len: usize, opts_json: *const c_char) -> i32 { - guarded(|| { - if bytes.is_null() { - return fail(FfiError::invalid("KDBX buffer is null")); - } - let slice = unsafe { std::slice::from_raw_parts(bytes, len) }; - match options_password(opts_json).and_then(|password| open_database(slice, &password)) { - Ok(_) => success(), - Err(error) => fail(error), - } - }) -} - -/// Create a new empty KDBX 4.0 database. `opts_json` is -/// `{"password":"...","name":"..."}`; output is a caller-owned byte buffer. -#[no_mangle] -pub extern "C" fn kp_create_database( - opts_json: *const c_char, - out_bytes: *mut *mut u8, - out_len: *mut usize, -) -> i32 { - guarded(|| { - if opts_json.is_null() || out_bytes.is_null() || out_len.is_null() { - return fail(FfiError::invalid("options or output pointer is null")); - } - let text = match unsafe { CStr::from_ptr(opts_json) }.to_str() { - Ok(text) => text, - Err(_) => return fail(FfiError::invalid("options JSON is not UTF-8")), - }; - let options: Value = match serde_json::from_str(text) { - Ok(value) => value, - Err(_) => return fail(FfiError::invalid("options JSON is invalid")), - }; - let password = match options.get("password").and_then(Value::as_str) { - Some(value) if !value.is_empty() => value, - _ => return fail(FfiError::invalid("password is required")), - }; - let name = options - .get("name") - .and_then(Value::as_str) - .unwrap_or("keepassity"); - match keepassity_core::kdbx::writer::create_empty(name, password) { - Ok(bytes) => { - set_buffer(out_bytes, out_len, bytes); - success() - } - Err(_) => fail(FfiError::new("IoError", "cannot create database")), - } - }) -} - -/// Decide the next sync action from remote metadata. -#[no_mangle] -pub extern "C" fn kp_sync_decide( - handle: *mut KpHandle, - remote_meta_json: *const c_char, - local_dirty: i32, - out_json: *mut *mut c_char, -) -> i32 { - guarded(|| { - if remote_meta_json.is_null() || out_json.is_null() { - return fail(FfiError::invalid("metadata or output pointer is null")); - } - let text = match unsafe { CStr::from_ptr(remote_meta_json) }.to_str() { - Ok(text) => text, - Err(_) => return fail(FfiError::invalid("metadata JSON is not UTF-8")), - }; - let remote: SyncRemoteMeta = match serde_json::from_str(text) { - Ok(remote) => remote, - Err(_) => return fail(FfiError::invalid("metadata JSON is invalid")), - }; - match with_state(handle, |state| { - state.dirty = local_dirty != 0; - let mut sync_state = SyncState::new(state.baseline.clone()); - sync_state.local_dirty = state.dirty; - let decision = sync_state.decide(&keepassity_core::sync::RemoteMeta { - etag: remote.etag, - size: remote.size, - modified_unix: remote.modified_unix, - sha256: None, - }); - Ok(json!({ - "action": action_name(decision.action), - "reason": decision.reason, - "degraded": decision.degraded, - "retry_after_ms": decision.retry_after_ms, - }) - .to_string()) - }) { - Ok(text) => match CString::new(text) { - Ok(value) => { - unsafe { - *out_json = value.into_raw(); - } - success() - } - Err(_) => fail(FfiError::internal("NUL in JSON")), - }, - Err(error) => fail(error), - } - }) -} - -/// Download remote bytes, merge, write the merged result and return conflicts. -#[no_mangle] -pub extern "C" fn kp_sync_merge( - handle: *mut KpHandle, - remote: *const u8, - len: usize, - out_bytes: *mut *mut u8, - out_len: *mut usize, - conflicts_json: *mut *mut c_char, -) -> i32 { - guarded(|| { - if remote.is_null() || out_bytes.is_null() || out_len.is_null() || conflicts_json.is_null() - { - return fail(FfiError::invalid("argument pointer is null")); - } - let remote_bytes = unsafe { std::slice::from_raw_parts(remote, len) }; - match with_state(handle, |state| { - let password = state.password.clone().ok_or_else(FfiError::locked)?; - let remote_db = open_database(remote_bytes, &password)?; - let local = state.database.as_ref().ok_or_else(FfiError::locked)?; - let merged = merge_for_sync(local, &remote_db); - let bytes = writer::write_model(&merged.database, &password) - .map_err(|_| FfiError::new("IoError", "cannot serialize merged database"))?; - let conflicts: Vec = - merged.conflicts.iter().map(ConflictItem::from).collect(); - let conflicts_text = serde_json::to_string(&conflicts) - .map_err(|_| FfiError::internal("cannot serialize conflicts"))?; - state.database = Some(merged.database); - state.dirty = true; - set_buffer(out_bytes, out_len, bytes); - unsafe { - *conflicts_json = CString::new(conflicts_text) - .map_err(|_| FfiError::internal("NUL in conflicts JSON"))? - .into_raw(); - } - Ok(()) - }) { - Ok(()) => success(), - Err(error) => fail(error), - } - }) -} - -/// Record a successful sync baseline. -#[no_mangle] -pub extern "C" fn kp_sync_commit( - handle: *mut KpHandle, - etag: *const c_char, - content_sha256: *const c_char, -) -> i32 { - guarded(|| { - let result = (|| { - let etag = c_string_opt(etag)?; - let sha = c_string_opt(content_sha256)?; - with_state(handle, |state| { - state.baseline = SyncBaseline { - etag, - sha256: sha, - size: None, - modified_unix: None, - }; - state.dirty = false; - state.last_sync_unix = Some(now_unix()); - Ok(()) - }) - })(); - match result { - Ok(()) => success(), - Err(error) => fail(error), - } - }) -} - -/// Mark local state dirty (unsaved/unuploaded edits). -#[no_mangle] -pub extern "C" fn kp_sync_mark_dirty(handle: *mut KpHandle) -> i32 { - guarded(|| { - match with_state(handle, |state| { - state.dirty = true; - Ok(()) - }) { - Ok(()) => success(), - Err(error) => fail(error), - } - }) -} - -/// Subscribe to events (v1 stores the callback; close/unsubscribe first). -#[no_mangle] -pub extern "C" fn kp_subscribe( - handle: *mut KpHandle, - callback: KpEventCb, - user: *mut c_void, -) -> i32 { - guarded(|| { - match with_state(handle, |state| { - state.subscriber = Some(Subscriber { - _callback: callback, - _user: user, - }); - Ok(()) - }) { - Ok(()) => success(), - Err(error) => fail(error), - } - }) -} - -/// Remove the event subscription. -#[no_mangle] -pub extern "C" fn kp_unsubscribe(handle: *mut KpHandle) -> i32 { - guarded(|| { - match with_state(handle, |state| { - state.subscriber = None; - Ok(()) - }) { - Ok(()) => success(), - Err(error) => fail(error), - } - }) -} - -fn c_string_opt(pointer: *const c_char) -> Result, FfiError> { - if pointer.is_null() { - return Ok(None); - } - unsafe { CStr::from_ptr(pointer) } - .to_str() - .map(|text| Some(text.to_string())) - .map_err(|_| FfiError::invalid("argument is not UTF-8")) -} - -fn action_name(action: SyncActionKind) -> &'static str { - match action { - SyncActionKind::UpToDate => "up_to_date", - SyncActionKind::Upload => "upload", - SyncActionKind::Download => "download", - SyncActionKind::DownloadAndMerge => "download_and_merge", - SyncActionKind::Retry => "retry", - SyncActionKind::Offline => "offline", - SyncActionKind::Conflict => "conflict", - } -} - -fn parse_uuid_arg(command: &Value, key: &str) -> Result { - let text = command - .get(key) - .and_then(Value::as_str) - .ok_or_else(|| FfiError::invalid(format!("{key} is required")))?; - parse_uuid(text).ok_or_else(|| FfiError::invalid(format!("{key} is invalid"))) -} - -fn parse_uuid(text: &str) -> Option { - let bytes = text.as_bytes(); - if bytes.len() != 32 { - return None; - } - let mut out = [0u8; 16]; - for index in 0..16 { - let high = (bytes[index * 2] as char).to_digit(16)?; - let low = (bytes[index * 2 + 1] as char).to_digit(16)?; - out[index] = (high * 16 + low) as u8; - } - Some(Uuid::from_bytes(out)) -} - -fn new_uuid() -> Uuid { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|duration| duration.as_nanos()) - .unwrap_or(0); - let mut bytes = [0u8; 16]; - bytes[..8].copy_from_slice(&(nanos as u64).to_le_bytes()); - bytes[8..12].copy_from_slice(&std::process::id().to_le_bytes()); - bytes[12..].copy_from_slice(&(nanos >> 64).to_le_bytes()[..4]); - bytes[6] = (bytes[6] & 0x0f) | 0x40; - bytes[8] = (bytes[8] & 0x3f) | 0x80; - Uuid::from_bytes(bytes) -} - -fn now_unix() -> i64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|duration| duration.as_secs() as i64) - .unwrap_or(0) -} - -fn touch(entry: &mut Entry, now: i64) { - let text = xml_datetime_from_unix(now); - entry.times.last_modification = text.clone(); - entry.times.last_access = text; -} - -fn set_field(entry: &mut Entry, key: &str, value: &str, protected: bool) { - if let Some(field) = entry.strings.iter_mut().find(|field| field.key == key) { - field.value = value.to_string(); - field.protected = protected; - return; - } - entry.strings.push(StringField { - key: key.to_string(), - value: value.to_string(), - protected, - unknown: Vec::new(), - }); -} - -fn entry_from_fields(uuid: Uuid, fields: &serde_json::Map) -> Entry { - let now = xml_datetime_from_unix(now_unix()); - let mut entry = Entry { - uuid, - times: Times { - creation: now.clone(), - last_modification: now.clone(), - last_access: now.clone(), - location_changed: now, - ..Times::default() - }, - ..Entry::default() - }; - for (key, value) in fields { - if let Some(text) = value.as_str() { - let protected = key == "Password" || key == "otp" || key.starts_with("TimeOtp-"); - set_field(&mut entry, key, text, protected); - } - } - entry -} - -fn apply_patch(entry: &mut Entry, patch: &serde_json::Map) { - for (key, value) in patch { - if key == "tags" { - entry.tags = value - .as_array() - .map(|values| { - values - .iter() - .filter_map(Value::as_str) - .map(str::to_string) - .collect() - }) - .unwrap_or_default(); - continue; - } - match value { - Value::Null => entry.strings.retain(|field| &field.key != key), - Value::String(text) => set_field(entry, key, text, key == "Password"), - _ => {} - } - } -} - -fn flatten_groups(database: &Database) -> Vec { - fn walk(group: &Group, parent: Option, order: &mut usize, out: &mut Vec) { - out.push(json!({ - "uuid": group.uuid.to_hex(), - "parent_uuid": parent.map(|uuid| uuid.to_hex()), - "name": group.name, - "icon": group.icon_id, - "order": *order, - })); - *order += 1; - for child in &group.groups { - walk(child, Some(group.uuid), order, out); - } - } - let mut out = Vec::new(); - let mut order = 0; - walk(&database.root, None, &mut order, &mut out); - out -} - -fn all_entries(database: &Database) -> Vec<(&Entry, Uuid)> { - fn walk<'a>(group: &'a Group, out: &mut Vec<(&'a Entry, Uuid)>) { - for entry in &group.entries { - out.push((entry, group.uuid)); - } - for child in &group.groups { - walk(child, out); - } - } - let mut out = Vec::new(); - walk(&database.root, &mut out); - out -} - -fn select_entries<'a>( - database: &'a Database, - group_uuid: Option<&str>, - include_subgroups: bool, -) -> Vec<(&'a Entry, Uuid)> { - let Some(text) = group_uuid else { - return all_entries(database); - }; - let Some(uuid) = parse_uuid(text) else { - return Vec::new(); - }; - let Some(group) = find_group(database, uuid) else { - return Vec::new(); - }; - let mut out = Vec::new(); - if include_subgroups { - fn walk<'a>(group: &'a Group, out: &mut Vec<(&'a Entry, Uuid)>) { - for entry in &group.entries { - out.push((entry, group.uuid)); - } - for child in &group.groups { - walk(child, out); - } - } - walk(group, &mut out); - } else { - for entry in &group.entries { - out.push((entry, group.uuid)); - } - } - out -} - -fn find_group(database: &Database, uuid: Uuid) -> Option<&Group> { - fn walk(group: &Group, uuid: Uuid) -> Option<&Group> { - if group.uuid == uuid { - return Some(group); - } - group.groups.iter().find_map(|child| walk(child, uuid)) - } - walk(&database.root, uuid) -} - -fn find_group_mut(database: &mut Database, uuid: Uuid) -> Option<&mut Group> { - fn walk(group: &mut Group, uuid: Uuid) -> Option<&mut Group> { - if group.uuid == uuid { - return Some(group); - } - group.groups.iter_mut().find_map(|child| walk(child, uuid)) - } - walk(&mut database.root, uuid) -} - -fn find_entry(database: &Database, uuid: Uuid) -> Option<(&Entry, Uuid)> { - fn walk(group: &Group, uuid: Uuid) -> Option<(&Entry, Uuid)> { - if let Some(entry) = group.entries.iter().find(|entry| entry.uuid == uuid) { - return Some((entry, group.uuid)); - } - group.groups.iter().find_map(|child| walk(child, uuid)) - } - walk(&database.root, uuid) -} - -fn find_entry_mut(database: &mut Database, uuid: Uuid) -> Option<(&mut Entry, Uuid)> { - fn walk(group: &mut Group, uuid: Uuid) -> Option<(&mut Entry, Uuid)> { - let parent = group.uuid; - if let Some(index) = group.entries.iter().position(|entry| entry.uuid == uuid) { - return Some((&mut group.entries[index], parent)); - } - group.groups.iter_mut().find_map(|child| walk(child, uuid)) - } - walk(&mut database.root, uuid) -} - -fn remove_entry(group: &mut Group, uuid: Uuid) -> Option<(Entry, Uuid)> { - let parent = group.uuid; - if let Some(index) = group.entries.iter().position(|entry| entry.uuid == uuid) { - return Some((group.entries.remove(index), parent)); - } - for child in &mut group.groups { - if let Some(found) = remove_entry(child, uuid) { - return Some(found); - } - } - None -} - -fn remove_group(group: &mut Group, uuid: Uuid) -> Option { - if let Some(index) = group.groups.iter().position(|child| child.uuid == uuid) { - return Some(group.groups.remove(index)); - } - for child in &mut group.groups { - if let Some(found) = remove_group(child, uuid) { - return Some(found); - } - } - None -} - -fn collect_group_tombstones(group: &Group, out: &mut Vec) { - out.push(group.uuid); - for entry in &group.entries { - out.push(entry.uuid); - } - for child in &group.groups { - collect_group_tombstones(child, out); - } -} - -fn parse_group_name(command: &Value) -> Result { - let name = command - .get("name") - .and_then(Value::as_str) - .map(str::trim) - .filter(|name| !name.is_empty()) - .ok_or_else(|| FfiError::invalid("group name is required"))?; - Ok(name.to_string()) -} - -fn database_stats(database: &Database) -> (usize, usize, usize, usize) { - fn walk(group: &Group, counts: &mut (usize, usize, usize, usize)) { - counts.0 += 1; - for entry in &group.entries { - counts.1 += 1; - counts.3 += entry.history.len(); - if entry.has_totp() { - counts.2 += 1; - } - } - for child in &group.groups { - walk(child, counts); - } - } - let mut counts = (0, 0, 0, 0); - walk(&database.root, &mut counts); - counts -} - -fn algorithm_name(algorithm: CoreTotpAlgorithm) -> &'static str { - match algorithm { - CoreTotpAlgorithm::Sha1 => "SHA1", - CoreTotpAlgorithm::Sha256 => "SHA256", - CoreTotpAlgorithm::Sha512 => "SHA512", - } -} - -fn core_totp_to_dto(spec: &totp_fields::TotpSpec) -> DtoTotpConfig { - let config = &spec.config; - DtoTotpConfig { - secret_base32: base32_encode(&config.secret), - issuer: spec.issuer.clone(), - account: spec.account.clone(), - algorithm: match config.algorithm { - CoreTotpAlgorithm::Sha1 => DtoTotpAlgorithm::Sha1, - CoreTotpAlgorithm::Sha256 => DtoTotpAlgorithm::Sha256, - CoreTotpAlgorithm::Sha512 => DtoTotpAlgorithm::Sha512, - }, - digits: config.digits, - period: config.period, - encoder: match config.encoder { - CoreTotpEncoder::Totp => DtoTotpEncoder::Totp, - CoreTotpEncoder::Steam => DtoTotpEncoder::Steam, - }, - counter: None, - } -} - -fn dto_to_totp_spec(value: &Value) -> Result { - let secret = value - .get("secret_base32") - .and_then(Value::as_str) - .ok_or_else(|| FfiError::invalid("secret_base32 is required"))?; - let secret_bytes = - base32_decode(secret).map_err(|error| FfiError::invalid(error.to_string()))?; - let algorithm = match value - .get("algorithm") - .and_then(Value::as_str) - .unwrap_or("SHA1") - { - "SHA256" => CoreTotpAlgorithm::Sha256, - "SHA512" => CoreTotpAlgorithm::Sha512, - _ => CoreTotpAlgorithm::Sha1, - }; - let encoder = match value - .get("encoder") - .and_then(Value::as_str) - .unwrap_or("totp") - { - "steam" => CoreTotpEncoder::Steam, - _ => CoreTotpEncoder::Totp, - }; - let config = CoreTotpConfig { - secret: secret_bytes, - algorithm, - digits: value - .get("digits") - .and_then(Value::as_u64) - .unwrap_or(6) - .clamp(1, 10) as u32, - period: value - .get("period") - .and_then(Value::as_u64) - .unwrap_or(30) - .clamp(1, 3_600) as u32, - encoder, - }; - Ok(totp_fields::TotpSpec { - config, - issuer: value - .get("issuer") - .and_then(Value::as_str) - .map(str::to_string), - account: value - .get("account") - .and_then(Value::as_str) - .map(str::to_string), - }) -} - -fn generate_password( - length: usize, - classes: Option<&Value>, - exclude_ambiguous: bool, -) -> Result<(String, f64), FfiError> { - let mut alphabet = String::new(); - let lower = classes - .and_then(|classes| classes.get("lowercase")) - .and_then(Value::as_bool) - .unwrap_or(true); - let upper = classes - .and_then(|classes| classes.get("uppercase")) - .and_then(Value::as_bool) - .unwrap_or(true); - let digits = classes - .and_then(|classes| classes.get("digits")) - .and_then(Value::as_bool) - .unwrap_or(true); - let symbols = classes - .and_then(|classes| classes.get("symbols")) - .and_then(Value::as_bool) - .unwrap_or(true); - if lower { - alphabet.push_str("abcdefghijklmnopqrstuvwxyz"); - } - if upper { - alphabet.push_str("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); - } - if digits { - alphabet.push_str("0123456789"); - } - if symbols { - alphabet.push_str("!@#$%^&*()-_=+[]{};:,.?/"); - } - if exclude_ambiguous { - alphabet.retain(|character| !"Il1O0o".contains(character)); - } - if alphabet.is_empty() { - return Err(FfiError::invalid("password charset is empty")); - } - let alphabet: Vec = alphabet.chars().collect(); - let mut bytes = vec![0u8; length * 4]; - fill_random(&mut bytes).map_err(|_| FfiError::new("Internal", "OS randomness unavailable"))?; - let mut password = String::with_capacity(length); - let mut index = 0; - while password.chars().count() < length { - let threshold = 256 - (256 % alphabet.len()); - let byte = bytes[index % bytes.len()]; - index += 1; - if usize::from(byte) < threshold { - password.push(alphabet[usize::from(byte) % alphabet.len()]); - } - } - let entropy = length as f64 * (alphabet.len() as f64).log2(); - Ok((password, entropy)) -} - -#[cfg(unix)] -fn fill_random(buffer: &mut [u8]) -> Result<(), ()> { - use std::fs::File; - use std::io::Read; - let mut file = File::open("/dev/urandom").map_err(|_| ())?; - file.read_exact(buffer).map_err(|_| ()) -} - -#[cfg(windows)] -#[link(name = "advapi32")] -extern "system" { - fn SystemFunction036(buffer: *mut u8, len: u32) -> u8; -} - -#[cfg(windows)] -fn fill_random(buffer: &mut [u8]) -> Result<(), ()> { - let len = u32::try_from(buffer.len()).map_err(|_| ())?; - let status = unsafe { SystemFunction036(buffer.as_mut_ptr(), len) }; - if status == 0 { - Err(()) - } else { - Ok(()) - } -} - -#[cfg(not(any(unix, windows)))] -fn fill_random(buffer: &mut [u8]) -> Result<(), ()> { - for (index, byte) in buffer.iter_mut().enumerate() { - *byte = (index.wrapping_mul(31) ^ (now_unix() as usize)) as u8; - } - Ok(()) -} - +mod abi; +mod dispatch; +mod json_helpers; +mod model_helpers; +mod password; #[cfg(test)] -mod tests { - use super::*; - - fn fixture() -> Vec { - std::fs::read(concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../tests/fixtures/keepass-rs/test_db_kdbx4_with_password_aes.kdbx" - )) - .expect("fixture") - } - - fn open_fixture() -> *mut KpHandle { - let bytes = fixture(); - let opts = CString::new(r#"{"password":"demopass"}"#).unwrap(); - let handle = kp_open(bytes.as_ptr(), bytes.len(), opts.as_ptr()); - assert!(!handle.is_null()); - handle - } - - fn fixture_bytes(name: &str) -> Vec { - std::fs::read(format!( - "{}/../../tests/fixtures/keepass-rs/{name}", - env!("CARGO_MANIFEST_DIR") - )) - .expect("fixture") - } - - fn open_bytes(bytes: &[u8], password: &str) -> *mut KpHandle { - let opts = CString::new(format!(r#"{{"password":"{password}"}}"#)).unwrap(); - let handle = kp_open(bytes.as_ptr(), bytes.len(), opts.as_ptr()); - assert!(!handle.is_null()); - handle - } - - fn parse(json_text: &str) -> Value { - serde_json::from_str(json_text).expect("valid command JSON") - } - - /// Assert a command fails and return its error JSON. - fn call_error(handle: *mut KpHandle, command: &str) -> String { - let command = CString::new(command).unwrap(); - let mut output = std::ptr::null_mut(); - assert_ne!( - kp_call(handle, command.as_ptr(), &mut output), - 0, - "command should fail: {command:?}" - ); - assert!(output.is_null()); - let error = unsafe { CStr::from_ptr(kp_last_error_json()) } - .to_str() - .expect("error JSON") - .to_string(); - assert!(!error.contains("demopass"), "error leaks the password"); - error - } - - fn call(handle: *mut KpHandle, command: &str) -> String { - let command = CString::new(command).unwrap(); - let mut output = std::ptr::null_mut(); - assert_eq!(kp_call(handle, command.as_ptr(), &mut output), 0); - assert!(!output.is_null()); - let text = unsafe { CStr::from_ptr(output) } - .to_str() - .unwrap() - .to_string(); - kp_string_free(output); - text - } - - #[test] - fn error_json_is_sanitized_and_cleared() { - let opts = CString::new(r#"{"password":"wrong"}"#).unwrap(); - let bytes = fixture(); - let handle = kp_open(bytes.as_ptr(), bytes.len(), opts.as_ptr()); - assert!(handle.is_null()); - let error = unsafe { CStr::from_ptr(kp_last_error_json()) } - .to_str() - .unwrap(); - assert!(error.contains("BadPassword")); - assert!(!error.contains("wrong")); - assert!(!error.contains("demopass")); - } - - #[test] - fn open_version_list_save_and_diagnose() { - let handle = open_fixture(); - let version: Value = - serde_json::from_str(&call(handle, r#"{"command":"version"}"#)).unwrap(); - assert_eq!(version["api"], 1); - let groups: Value = - serde_json::from_str(&call(handle, r#"{"command":"list_groups"}"#)).unwrap(); - assert!(groups.as_array().is_some_and(|groups| !groups.is_empty())); - let entries: Value = - serde_json::from_str(&call(handle, r#"{"command":"list_entries"}"#)).unwrap(); - assert!(entries - .as_array() - .is_some_and(|entries| !entries.is_empty())); - let diagnose: Value = - serde_json::from_str(&call(handle, r#"{"command":"diagnose"}"#)).unwrap(); - assert!(diagnose["entries"].as_u64().unwrap() > 0); - - let mut saved = std::ptr::null_mut(); - let mut saved_len = 0usize; - assert_eq!(kp_save(handle, &mut saved, &mut saved_len), 0); - assert!(!saved.is_null() && saved_len > 0); - let verify_opts = CString::new(r#"{"password":"demopass"}"#).unwrap(); - assert_eq!(kp_verify(saved, saved_len, verify_opts.as_ptr()), 0); - kp_buffer_free(saved, saved_len); - assert_eq!(kp_close(handle), 0); - } - - #[test] - fn null_and_locked_paths_do_not_panic() { - assert_ne!(kp_close(std::ptr::null_mut()), 0); - assert_ne!(kp_lock(std::ptr::null_mut()), 0); - let handle = open_fixture(); - assert_eq!(kp_lock(handle), 0); - let command = CString::new(r#"{"command":"list_entries"}"#).unwrap(); - let mut output = std::ptr::null_mut(); - assert_ne!(kp_call(handle, command.as_ptr(), &mut output), 0); - assert_eq!(kp_close(handle), 0); - } - - #[test] - fn crud_and_totp_commands_smoke() { - let handle = open_fixture(); - let groups: Value = - serde_json::from_str(&call(handle, r#"{"command":"list_groups"}"#)).unwrap(); - let group_uuid = groups[0]["uuid"].as_str().unwrap().to_string(); - let create = format!( - r#"{{"command":"create_entry","group_uuid":"{}","fields":{{"Title":"ffi-created","UserName":"u","Password":"p"}}}}"#, - group_uuid - ); - let created: Value = serde_json::from_str(&call(handle, &create)).unwrap(); - let entry_uuid = created["uuid"].as_str().unwrap().to_string(); - let get = format!(r#"{{"command":"get_entry","uuid":"{}"}}"#, entry_uuid); - let full: Value = serde_json::from_str(&call(handle, &get)).unwrap(); - assert_eq!(full["title"], "ffi-created"); - let update = format!( - r#"{{"command":"update_entry","uuid":"{}","patch":{{"Title":"ffi-updated"}}}}"#, - entry_uuid - ); - let _: Value = serde_json::from_str(&call(handle, &update)).unwrap(); - let set_totp = format!( - r#"{{"command":"totp_set","uuid":"{}","config":{{"secret_base32":"JBSWY3DPEHPK3PXP","algorithm":"SHA1","digits":6,"period":30,"encoder":"totp"}}}}"#, - entry_uuid - ); - let _: Value = serde_json::from_str(&call(handle, &set_totp)).unwrap(); - let code = format!( - r#"{{"command":"totp_code","uuid":"{}","at_unix":0}}"#, - entry_uuid - ); - let code: Value = serde_json::from_str(&call(handle, &code)).unwrap(); - assert_eq!(code["code"].as_str().unwrap().len(), 6); - let delete_totp = format!(r#"{{"command":"totp_delete","uuid":"{}"}}"#, entry_uuid); - let _: Value = serde_json::from_str(&call(handle, &delete_totp)).unwrap(); - let delete = format!( - r#"{{"command":"delete_entry","uuid":"{}","permanent":true}}"#, - entry_uuid - ); - let _: Value = serde_json::from_str(&call(handle, &delete)).unwrap(); - assert_eq!(kp_close(handle), 0); - } - - #[test] - fn password_generate_honours_options_and_reports_consistent_entropy() { - let handle = open_fixture(); - - // Lowercase + digits without ambiguous look-alikes: 24 + 8 = 32 - // symbols, i.e. exactly 5 bits per character -> 160 bits for 32 chars. - let generated = parse(&call( - handle, - r#"{"command":"password_generate","length":32,"classes":{"lowercase":true,"uppercase":false,"digits":true,"symbols":false},"exclude_ambiguous":true}"#, - )); - let password = generated["password"].as_str().expect("password string"); - assert_eq!(password.chars().count(), 32); - assert!(password - .chars() - .all(|character| character.is_ascii_lowercase() || character.is_ascii_digit())); - assert!( - password - .chars() - .all(|character| !"Il1O0o".contains(character)), - "ambiguous characters must be excluded: {password}" - ); - assert_eq!(generated["entropy_bits"].as_f64(), Some(160.0)); - - // Digits only, ambiguous excluded: "23456789" -> 3 bits per char. - let digits_only = parse(&call( - handle, - r#"{"command":"password_generate","length":16,"classes":{"lowercase":false,"uppercase":false,"digits":true,"symbols":false},"exclude_ambiguous":true}"#, - )); - let password = digits_only["password"].as_str().expect("password string"); - assert_eq!(password.len(), 16); - assert!(password - .chars() - .all(|character| ('2'..='9').contains(&character))); - assert_eq!(digits_only["entropy_bits"].as_f64(), Some(48.0)); - - // The same digits-only charset without the exclusion has 10 symbols; - // entropy must grow accordingly (10 * log2(10) for 10 characters). - let digits_without_exclusion = parse(&call( - handle, - r#"{"command":"password_generate","length":10,"classes":{"lowercase":false,"uppercase":false,"digits":true,"symbols":false},"exclude_ambiguous":false}"#, - )); - let password = digits_without_exclusion["password"] - .as_str() - .expect("password string"); - assert_eq!(password.len(), 10); - assert!(password.chars().all(|character| character.is_ascii_digit())); - let expected = 10.0 * 10.0_f64.log2(); - assert_eq!( - digits_without_exclusion["entropy_bits"].as_f64(), - Some(expected) - ); - assert_ne!( - digits_only["entropy_bits"].as_f64(), - digits_without_exclusion["entropy_bits"].as_f64() - ); - - // All classes enabled: 26 lower + 26 upper + 10 digits + 24 symbols = 86. - let everything = parse(&call( - handle, - r#"{"command":"password_generate","length":12,"classes":{"lowercase":true,"uppercase":true,"digits":true,"symbols":true},"exclude_ambiguous":false}"#, - )); - assert_eq!(everything["password"].as_str().unwrap().chars().count(), 12); - let expected = 12.0 * 86.0_f64.log2(); - assert_eq!(everything["entropy_bits"].as_f64(), Some(expected)); - - // No character class selected must be rejected, not silently generated. - let error = call_error( - handle, - r#"{"command":"password_generate","length":8,"classes":{"lowercase":false,"uppercase":false,"digits":false,"symbols":false}}"#, - ); - assert!( - error.contains("InvalidArgument"), - "unexpected error: {error}" - ); - assert!( - error.contains("charset is empty"), - "unexpected error: {error}" - ); - - assert_eq!(kp_close(handle), 0); - } - - #[test] - fn totp_code_at_unix_uses_the_requested_window() { - let bytes = fixture_bytes("test_db_kdbx4_with_totp_entry.kdbx"); - let handle = open_bytes(&bytes, "test"); - - let entries = parse(&call(handle, r#"{"command":"list_entries"}"#)); - let uuid = entries - .as_array() - .expect("entry list") - .iter() - .find(|entry| entry["has_totp"].as_bool() == Some(true)) - .and_then(|entry| entry["uuid"].as_str()) - .expect("fixture has a TOTP entry") - .to_string(); - let full = parse(&call( - handle, - &format!(r#"{{"command":"get_entry","uuid":"{uuid}"}}"#), - )); - assert_eq!(full["title"].as_str(), Some("this entry has totp")); - let config = &full["totp"]; - // Public fixture configuration: otpauth://totp/KeePassXC:none - // ?secret=JBSWY3DPEHPK3PXP&period=30&digits=6 (SHA-1). - assert_eq!(config["secret_base32"].as_str(), Some("JBSWY3DPEHPK3PXP")); - assert_eq!(config["algorithm"].as_str(), Some("SHA1")); - assert_eq!(config["digits"].as_u64(), Some(6)); - assert_eq!(config["period"].as_u64(), Some(30)); - - // Reference codes for RFC 6238 TOTP-SHA1 / 6 digits / 30 s with the - // fixture secret, computed by an independent implementation: - // (at_unix, code, seconds remaining in the window). - let cases: [(u64, &str, u64); 8] = [ - (0, "282760", 30), - (29, "282760", 1), - (30, "996554", 30), - (59, "996554", 1), - (1_700_000_000, "324550", 10), - (1_700_000_009, "324550", 1), - (1_700_000_010, "367665", 30), - (1_700_000_040, "870960", 30), - ]; - for (at_unix, expected_code, expected_remaining) in cases { - let code = parse(&call( - handle, - &format!(r#"{{"command":"totp_code","uuid":"{uuid}","at_unix":{at_unix}}}"#), - )); - assert_eq!( - code["code"].as_str(), - Some(expected_code), - "code at at_unix={at_unix}" - ); - assert_eq!( - code["remaining"].as_u64(), - Some(expected_remaining), - "remaining at at_unix={at_unix}" - ); - assert_eq!(code["period"].as_u64(), Some(30)); - assert_eq!(code["digits"].as_u64(), Some(6)); - assert_eq!(code["algorithm"].as_str(), Some("SHA1")); - assert_eq!(code["skew_warning"].as_bool(), Some(false)); - } - - // Same window keeps the code stable, a step boundary rotates it. - let window_start = parse(&call( - handle, - &format!(r#"{{"command":"totp_code","uuid":"{uuid}","at_unix":0}}"#), - )); - let window_end = parse(&call( - handle, - &format!(r#"{{"command":"totp_code","uuid":"{uuid}","at_unix":29}}"#), - )); - let next_window = parse(&call( - handle, - &format!(r#"{{"command":"totp_code","uuid":"{uuid}","at_unix":30}}"#), - )); - assert_eq!(window_start["code"], window_end["code"]); - assert_ne!(window_start["code"], next_window["code"]); - assert_eq!(window_start["remaining"].as_u64(), Some(30)); - assert_eq!(window_end["remaining"].as_u64(), Some(1)); - assert_eq!(next_window["remaining"].as_u64(), Some(30)); - - assert_eq!(kp_close(handle), 0); - } - - #[test] - fn api_version_matches_core() { - assert_eq!(kp_api_version(), keepassity_core::API_MAJOR); - } -} +mod tests; +mod totp_helpers; + +// The modules are re-exported inside the crate so the ABI layer, the dispatcher +// and the tests share one flat namespace, exactly as the single file did. None +// of this is public API: the exported C symbols are the contract. +pub(crate) use dispatch::*; +pub(crate) use json_helpers::*; +pub(crate) use model_helpers::*; +pub(crate) use password::*; +pub(crate) use totp_helpers::*; diff --git a/crates/ffi/src/model_helpers.rs b/crates/ffi/src/model_helpers.rs new file mode 100644 index 0000000..fc0cd9f --- /dev/null +++ b/crates/ffi/src/model_helpers.rs @@ -0,0 +1,329 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Model helpers: UUID parsing, lookups, field patches, flattening and +//! the recycle bin rules shared by several commands. + +use super::*; + +pub(crate) fn action_name(action: SyncActionKind) -> &'static str { + match action { + SyncActionKind::UpToDate => "up_to_date", + SyncActionKind::Upload => "upload", + SyncActionKind::Download => "download", + SyncActionKind::DownloadAndMerge => "download_and_merge", + SyncActionKind::Retry => "retry", + SyncActionKind::Offline => "offline", + SyncActionKind::Conflict => "conflict", + } +} + +pub(crate) fn parse_uuid_arg(command: &Value, key: &str) -> Result { + let text = command + .get(key) + .and_then(Value::as_str) + .ok_or_else(|| FfiError::invalid(format!("{key} is required")))?; + parse_uuid(text).ok_or_else(|| FfiError::invalid(format!("{key} is invalid"))) +} + +pub(crate) fn parse_uuid(text: &str) -> Option { + let bytes = text.as_bytes(); + if bytes.len() != 32 { + return None; + } + let mut out = [0u8; 16]; + for index in 0..16 { + let high = (bytes[index * 2] as char).to_digit(16)?; + let low = (bytes[index * 2 + 1] as char).to_digit(16)?; + out[index] = (high * 16 + low) as u8; + } + Some(Uuid::from_bytes(out)) +} + +pub(crate) fn new_uuid() -> Uuid { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|duration| duration.as_nanos()) + .unwrap_or(0); + let mut bytes = [0u8; 16]; + bytes[..8].copy_from_slice(&(nanos as u64).to_le_bytes()); + bytes[8..12].copy_from_slice(&std::process::id().to_le_bytes()); + bytes[12..].copy_from_slice(&(nanos >> 64).to_le_bytes()[..4]); + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + Uuid::from_bytes(bytes) +} + +pub(crate) fn now_unix() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|duration| duration.as_secs() as i64) + .unwrap_or(0) +} + +pub(crate) fn touch(entry: &mut Entry, now: i64) { + let text = xml_datetime_from_unix(now); + entry.times.last_modification = text.clone(); + entry.times.last_access = text; +} + +pub(crate) fn set_field(entry: &mut Entry, key: &str, value: &str, protected: bool) { + if let Some(field) = entry.strings.iter_mut().find(|field| field.key == key) { + field.value = value.to_string(); + // An existing protection flag is a property of the file, not of this + // call: a generic update path must never turn a protected secret into + // plaintext by passing `false`. New fields take the caller's default. + return; + } + entry.strings.push(StringField { + key: key.to_string(), + value: value.to_string(), + protected, + unknown: Vec::new(), + }); +} + +pub(crate) fn entry_from_fields(uuid: Uuid, fields: &serde_json::Map) -> Entry { + let now = xml_datetime_from_unix(now_unix()); + let mut entry = Entry { + uuid, + times: Times { + creation: now.clone(), + last_modification: now.clone(), + last_access: now.clone(), + location_changed: now, + ..Times::default() + }, + ..Entry::default() + }; + for (key, value) in fields { + if let Some(text) = value.as_str() { + let protected = key == "Password" || key == "otp" || key.starts_with("TimeOtp-"); + set_field(&mut entry, key, text, protected); + } + } + entry +} + +pub(crate) fn apply_patch(entry: &mut Entry, patch: &serde_json::Map) { + for (key, value) in patch { + if key == "tags" { + entry.tags = value + .as_array() + .map(|values| { + values + .iter() + .filter_map(Value::as_str) + .map(str::to_string) + .collect() + }) + .unwrap_or_default(); + continue; + } + match value { + Value::Null => entry.strings.retain(|field| &field.key != key), + // Existing fields keep their flag (see `set_field`); a field added + // by a patch is unprotected by default. The create path is what + // marks Password/OTP fields protected. + Value::String(text) => set_field(entry, key, text, false), + _ => {} + } + } +} + +pub(crate) fn flatten_groups(database: &Database) -> Vec { + fn walk(group: &Group, parent: Option, order: &mut usize, out: &mut Vec) { + out.push(json!({ + "uuid": group.uuid.to_hex(), + "parent_uuid": parent.map(|uuid| uuid.to_hex()), + "name": group.name, + "icon": group.icon_id, + "order": *order, + })); + *order += 1; + for child in &group.groups { + walk(child, Some(group.uuid), order, out); + } + } + let mut out = Vec::new(); + let mut order = 0; + walk(&database.root, None, &mut order, &mut out); + out +} + +pub(crate) fn all_entries(database: &Database) -> Vec<(&Entry, Uuid)> { + fn walk<'a>(group: &'a Group, out: &mut Vec<(&'a Entry, Uuid)>) { + for entry in &group.entries { + out.push((entry, group.uuid)); + } + for child in &group.groups { + walk(child, out); + } + } + let mut out = Vec::new(); + walk(&database.root, &mut out); + out +} + +pub(crate) fn select_entries<'a>( + database: &'a Database, + group_uuid: Option<&str>, + include_subgroups: bool, +) -> Vec<(&'a Entry, Uuid)> { + let Some(text) = group_uuid else { + return all_entries(database); + }; + let Some(uuid) = parse_uuid(text) else { + return Vec::new(); + }; + let Some(group) = find_group(database, uuid) else { + return Vec::new(); + }; + let mut out = Vec::new(); + if include_subgroups { + fn walk<'a>(group: &'a Group, out: &mut Vec<(&'a Entry, Uuid)>) { + for entry in &group.entries { + out.push((entry, group.uuid)); + } + for child in &group.groups { + walk(child, out); + } + } + walk(group, &mut out); + } else { + for entry in &group.entries { + out.push((entry, group.uuid)); + } + } + out +} + +pub(crate) fn find_group(database: &Database, uuid: Uuid) -> Option<&Group> { + fn walk(group: &Group, uuid: Uuid) -> Option<&Group> { + if group.uuid == uuid { + return Some(group); + } + group.groups.iter().find_map(|child| walk(child, uuid)) + } + walk(&database.root, uuid) +} + +pub(crate) fn find_group_mut(database: &mut Database, uuid: Uuid) -> Option<&mut Group> { + fn walk(group: &mut Group, uuid: Uuid) -> Option<&mut Group> { + if group.uuid == uuid { + return Some(group); + } + group.groups.iter_mut().find_map(|child| walk(child, uuid)) + } + walk(&mut database.root, uuid) +} + +pub(crate) fn find_entry(database: &Database, uuid: Uuid) -> Option<(&Entry, Uuid)> { + fn walk(group: &Group, uuid: Uuid) -> Option<(&Entry, Uuid)> { + if let Some(entry) = group.entries.iter().find(|entry| entry.uuid == uuid) { + return Some((entry, group.uuid)); + } + group.groups.iter().find_map(|child| walk(child, uuid)) + } + walk(&database.root, uuid) +} + +pub(crate) fn find_entry_mut(database: &mut Database, uuid: Uuid) -> Option<(&mut Entry, Uuid)> { + fn walk(group: &mut Group, uuid: Uuid) -> Option<(&mut Entry, Uuid)> { + let parent = group.uuid; + if let Some(index) = group.entries.iter().position(|entry| entry.uuid == uuid) { + return Some((&mut group.entries[index], parent)); + } + group.groups.iter_mut().find_map(|child| walk(child, uuid)) + } + walk(&mut database.root, uuid) +} + +pub(crate) fn remove_entry(group: &mut Group, uuid: Uuid) -> Option<(Entry, Uuid)> { + let parent = group.uuid; + if let Some(index) = group.entries.iter().position(|entry| entry.uuid == uuid) { + return Some((group.entries.remove(index), parent)); + } + for child in &mut group.groups { + if let Some(found) = remove_entry(child, uuid) { + return Some(found); + } + } + None +} + +pub(crate) fn remove_group(group: &mut Group, uuid: Uuid) -> Option { + if let Some(index) = group.groups.iter().position(|child| child.uuid == uuid) { + return Some(group.groups.remove(index)); + } + for child in &mut group.groups { + if let Some(found) = remove_group(child, uuid) { + return Some(found); + } + } + None +} + +pub(crate) fn collect_group_tombstones(group: &Group, out: &mut Vec) { + out.push(group.uuid); + for entry in &group.entries { + out.push(entry.uuid); + } + for child in &group.groups { + collect_group_tombstones(child, out); + } +} + +/// True when `uuid` is `group` itself or somewhere in its subtree. +pub(crate) fn group_contains_uuid(group: &Group, uuid: Uuid) -> bool { + group.uuid == uuid + || group + .groups + .iter() + .any(|child| group_contains_uuid(child, uuid)) +} + +/// Return the recycle-bin group, creating it when the database enables the +/// recycle bin but has no usable group UUID. A new database used to have a nil +/// UUID, so deleting an entry silently produced a permanent tombstone while the +/// UI promised a recycle bin. +pub(crate) fn ensure_recycle_bin(database: &mut Database) -> Option { + if !database.meta.recycle_bin_enabled { + return None; + } + if let Some(uuid) = database.meta.recycle_bin_uuid { + if uuid != database.root.uuid && find_group(database, uuid).is_some() { + return Some(uuid); + } + } + // Adopt an existing group with KeePass's standard name instead of creating + // a second one next to it. + if let Some(uuid) = database + .root + .groups + .iter() + .find(|group| group.name == "Recycle Bin") + .map(|group| group.uuid) + { + database.meta.recycle_bin_uuid = Some(uuid); + return Some(uuid); + } + let uuid = new_uuid(); + let now = xml_datetime_from_unix(now_unix()); + database.meta.recycle_bin_uuid = Some(uuid); + database.meta.recycle_bin_changed = Some(now.clone()); + database.root.groups.push(Group { + uuid, + name: "Recycle Bin".to_string(), + icon_id: 43, + times: Times { + creation: now.clone(), + last_modification: now.clone(), + last_access: now.clone(), + expiry: now.clone(), + location_changed: now, + ..Times::default() + }, + is_expanded: false, + ..Group::default() + }); + Some(uuid) +} diff --git a/crates/ffi/src/password.rs b/crates/ffi/src/password.rs new file mode 100644 index 0000000..0e974cb --- /dev/null +++ b/crates/ffi/src/password.rs @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Password generation and the platform CSPRNG that seeds it. + +use super::*; + +pub(crate) fn generate_password( + length: usize, + classes: Option<&Value>, + exclude_ambiguous: bool, +) -> Result<(String, f64), FfiError> { + let mut alphabet = String::new(); + let lower = classes + .and_then(|classes| classes.get("lowercase")) + .and_then(Value::as_bool) + .unwrap_or(true); + let upper = classes + .and_then(|classes| classes.get("uppercase")) + .and_then(Value::as_bool) + .unwrap_or(true); + let digits = classes + .and_then(|classes| classes.get("digits")) + .and_then(Value::as_bool) + .unwrap_or(true); + let symbols = classes + .and_then(|classes| classes.get("symbols")) + .and_then(Value::as_bool) + .unwrap_or(true); + if lower { + alphabet.push_str("abcdefghijklmnopqrstuvwxyz"); + } + if upper { + alphabet.push_str("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + } + if digits { + alphabet.push_str("0123456789"); + } + if symbols { + alphabet.push_str("!@#$%^&*()-_=+[]{};:,.?/"); + } + if exclude_ambiguous { + alphabet.retain(|character| !"Il1O0o".contains(character)); + } + if alphabet.is_empty() { + return Err(FfiError::invalid("password charset is empty")); + } + let alphabet: Vec = alphabet.chars().collect(); + let mut bytes = vec![0u8; length * 4]; + fill_random(&mut bytes).map_err(|_| FfiError::new("Internal", "OS randomness unavailable"))?; + let mut password = String::with_capacity(length); + let mut index = 0; + while password.chars().count() < length { + let threshold = 256 - (256 % alphabet.len()); + let byte = bytes[index % bytes.len()]; + index += 1; + if usize::from(byte) < threshold { + password.push(alphabet[usize::from(byte) % alphabet.len()]); + } + } + let entropy = length as f64 * (alphabet.len() as f64).log2(); + Ok((password, entropy)) +} + +#[cfg(unix)] +pub(crate) fn fill_random(buffer: &mut [u8]) -> Result<(), ()> { + use std::fs::File; + use std::io::Read; + let mut file = File::open("/dev/urandom").map_err(|_| ())?; + file.read_exact(buffer).map_err(|_| ()) +} + +#[cfg(windows)] +#[link(name = "advapi32")] +extern "system" { + fn SystemFunction036(buffer: *mut u8, len: u32) -> u8; +} + +#[cfg(windows)] +pub(crate) fn fill_random(buffer: &mut [u8]) -> Result<(), ()> { + let len = u32::try_from(buffer.len()).map_err(|_| ())?; + let status = unsafe { SystemFunction036(buffer.as_mut_ptr(), len) }; + if status == 0 { + Err(()) + } else { + Ok(()) + } +} + +#[cfg(not(any(unix, windows)))] +pub(crate) fn fill_random(buffer: &mut [u8]) -> Result<(), ()> { + for (index, byte) in buffer.iter_mut().enumerate() { + *byte = (index.wrapping_mul(31) ^ (now_unix() as usize)) as u8; + } + Ok(()) +} diff --git a/crates/ffi/src/tests/entries.rs b/crates/ffi/src/tests/entries.rs new file mode 100644 index 0000000..0a1ddc9 --- /dev/null +++ b/crates/ffi/src/tests/entries.rs @@ -0,0 +1,191 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Entry CRUD, patches, history limits and moves. + +use super::*; + +pub(crate) fn first_group_uuid(handle: *mut KpHandle) -> String { + let groups: Value = + serde_json::from_str(&call(handle, r#"{"command":"list_groups"}"#)).unwrap(); + groups[0]["uuid"].as_str().expect("group uuid").to_string() +} + +pub(crate) fn create_entry_in(handle: *mut KpHandle, group_uuid: &str, fields: &str) -> String { + let command = + format!(r#"{{"command":"create_entry","group_uuid":"{group_uuid}","fields":{fields}}}"#); + let created: Value = serde_json::from_str(&call(handle, &command)).unwrap(); + created["uuid"].as_str().expect("entry uuid").to_string() +} + +/// Clone one entry out of the open handle (test-only access to the model). +pub(crate) fn state_entry(handle: *mut KpHandle, uuid: Uuid) -> Entry { + let handle = unsafe { &*handle }; + let state = handle.state.lock().expect("handle lock"); + let database = state.database.as_ref().expect("open database"); + find_entry(database, uuid) + .expect("entry in model") + .0 + .clone() +} + +pub(crate) fn set_history_limits(handle: *mut KpHandle, max_items: i64, max_size: i64) { + let handle = unsafe { &*handle }; + let mut state = handle.state.lock().expect("handle lock"); + let database = state.database.as_mut().expect("open database"); + database.meta.history_max_items = max_items; + database.meta.history_max_size = max_size; +} + +pub(crate) fn update_field(handle: *mut KpHandle, uuid: &str, key: &str, value: &str) { + let command = + format!(r#"{{"command":"update_entry","uuid":"{uuid}","patch":{{"{key}":"{value}"}}}}"#); + let _: Value = serde_json::from_str(&call(handle, &command)).unwrap(); +} + +#[test] +pub(crate) fn update_entry_records_old_password_in_history() { + let handle = open_fixture(); + let group = first_group_uuid(handle); + let uuid_text = create_entry_in( + handle, + &group, + r#"{"Title":"history-test","UserName":"u","Password":"old-password"}"#, + ); + let uuid = parse_uuid(&uuid_text).expect("uuid"); + + update_field(handle, &uuid_text, "Password", "new-password"); + + let full: Value = serde_json::from_str(&call( + handle, + &format!(r#"{{"command":"get_entry","uuid":"{uuid_text}"}}"#), + )) + .unwrap(); + assert_eq!(full["history_count"], 1); + + let entry = state_entry(handle, uuid); + assert_eq!(entry.field("Password"), Some("new-password")); + assert_eq!(entry.history.len(), 1); + assert_eq!(entry.history[0].field("Password"), Some("old-password")); + assert!( + entry.history[0].history.is_empty(), + "history snapshots must not nest history" + ); + assert_eq!(entry.history[0].previous_parent_group, None); + assert!( + entry + .strings + .iter() + .find(|field| field.key == "Password") + .is_some_and(|field| field.protected), + "an existing protected password must stay protected" + ); + assert_eq!(kp_close(handle), 0); +} + +#[test] +pub(crate) fn update_entry_patch_keeps_existing_protected_flag() { + let handle = open_fixture(); + let group = first_group_uuid(handle); + let uuid_text = create_entry_in( + handle, + &group, + r#"{"Title":"otp-protected","otp":"JBSWY3DPEHPK3PXP"}"#, + ); + let uuid = parse_uuid(&uuid_text).expect("uuid"); + let before = state_entry(handle, uuid); + assert!( + before + .strings + .iter() + .find(|field| field.key == "otp") + .is_some_and(|field| field.protected), + "create must store otp as protected" + ); + + update_field(handle, &uuid_text, "otp", "JBSWY3DPEHPK3PXQ"); + + let entry = state_entry(handle, uuid); + let otp = entry + .strings + .iter() + .find(|field| field.key == "otp") + .expect("otp field"); + assert_eq!(otp.value, "JBSWY3DPEHPK3PXQ"); + assert!( + otp.protected, + "a generic patch must not turn a protected field into plaintext" + ); + assert_eq!(kp_close(handle), 0); +} + +#[test] +pub(crate) fn update_entry_respects_history_item_limit() { + let handle = open_fixture(); + set_history_limits(handle, 2, -1); + let group = first_group_uuid(handle); + let uuid_text = create_entry_in( + handle, + &group, + r#"{"Title":"history-limit","Password":"p0"}"#, + ); + let uuid = parse_uuid(&uuid_text).expect("uuid"); + for password in ["p1", "p2", "p3"] { + update_field(handle, &uuid_text, "Password", password); + } + + let entry = state_entry(handle, uuid); + assert_eq!(entry.field("Password"), Some("p3")); + assert_eq!(entry.history.len(), 2); + assert_eq!(entry.history[0].field("Password"), Some("p1")); + assert_eq!(entry.history[1].field("Password"), Some("p2")); + assert_eq!(kp_close(handle), 0); +} + +#[test] +pub(crate) fn update_entry_respects_history_size_limit() { + let handle = open_fixture(); + set_history_limits(handle, -1, 0); + let group = first_group_uuid(handle); + let uuid_text = create_entry_in( + handle, + &group, + r#"{"Title":"history-size","Password":"p0"}"#, + ); + let uuid = parse_uuid(&uuid_text).expect("uuid"); + + update_field(handle, &uuid_text, "Password", "p1"); + + let entry = state_entry(handle, uuid); + assert_eq!(entry.field("Password"), Some("p1")); + assert!( + entry.history.is_empty(), + "a zero size limit must keep no history" + ); + assert_eq!(kp_close(handle), 0); +} + +#[test] +pub(crate) fn move_entry_to_missing_group_keeps_the_entry() { + let handle = open_fixture(); + let group = first_group_uuid(handle); + let uuid_text = create_entry_in( + handle, + &group, + r#"{"Title":"move-me","UserName":"u","Password":"p"}"#, + ); + let missing = "ffffffffffffffffffffffffffffffff"; + let error = call_error( + handle, + &format!(r#"{{"command":"move_entry","uuid":"{uuid_text}","group_uuid":"{missing}"}}"#), + ); + assert!(error.contains("NotFound"), "unexpected error: {error}"); + + // The failed move must not have removed the entry from the model. + let full: Value = serde_json::from_str(&call( + handle, + &format!(r#"{{"command":"get_entry","uuid":"{uuid_text}"}}"#), + )) + .unwrap(); + assert_eq!(full["title"], "move-me"); + assert_eq!(full["group_uuid"], group); + assert_eq!(kp_close(handle), 0); +} diff --git a/crates/ffi/src/tests/helpers.rs b/crates/ffi/src/tests/helpers.rs new file mode 100644 index 0000000..3023525 --- /dev/null +++ b/crates/ffi/src/tests/helpers.rs @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Shared fixtures and call helpers for the ABI tests. + +use super::*; + +pub(crate) fn fixture() -> Vec { + std::fs::read(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../tests/fixtures/keepass-rs/test_db_kdbx4_with_password_aes.kdbx" + )) + .expect("fixture") +} + +pub(crate) fn open_fixture() -> *mut KpHandle { + let bytes = fixture(); + let opts = CString::new(r#"{"password":"demopass"}"#).unwrap(); + let handle = kp_open(bytes.as_ptr(), bytes.len(), opts.as_ptr()); + assert!(!handle.is_null()); + handle +} + +pub(crate) fn fixture_bytes(name: &str) -> Vec { + std::fs::read(format!( + "{}/../../tests/fixtures/keepass-rs/{name}", + env!("CARGO_MANIFEST_DIR") + )) + .expect("fixture") +} + +pub(crate) fn open_bytes(bytes: &[u8], password: &str) -> *mut KpHandle { + let opts = CString::new(format!(r#"{{"password":"{password}"}}"#)).unwrap(); + let handle = kp_open(bytes.as_ptr(), bytes.len(), opts.as_ptr()); + assert!(!handle.is_null()); + handle +} + +pub(crate) fn parse(json_text: &str) -> Value { + serde_json::from_str(json_text).expect("valid command JSON") +} + +/// Assert a command fails and return its error JSON. +pub(crate) fn call_error(handle: *mut KpHandle, command: &str) -> String { + let command = CString::new(command).unwrap(); + let mut output = std::ptr::null_mut(); + assert_ne!( + kp_call(handle, command.as_ptr(), &mut output), + 0, + "command should fail: {command:?}" + ); + assert!(output.is_null()); + let error = unsafe { CStr::from_ptr(kp_last_error_json()) } + .to_str() + .expect("error JSON") + .to_string(); + assert!(!error.contains("demopass"), "error leaks the password"); + error +} + +pub(crate) fn call(handle: *mut KpHandle, command: &str) -> String { + let command = CString::new(command).unwrap(); + let mut output = std::ptr::null_mut(); + assert_eq!(kp_call(handle, command.as_ptr(), &mut output), 0); + assert!(!output.is_null()); + let text = unsafe { CStr::from_ptr(output) } + .to_str() + .unwrap() + .to_string(); + kp_string_free(output); + text +} diff --git a/crates/ffi/src/tests/mod.rs b/crates/ffi/src/tests/mod.rs new file mode 100644 index 0000000..b33b826 --- /dev/null +++ b/crates/ffi/src/tests/mod.rs @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! End-to-end checks of the C ABI through the real JSON commands. +use super::*; +use crate::abi::*; + +mod entries; +mod helpers; +mod recycle; +mod surface; +mod sync_kdf; +mod totp_password; + +// Re-exported so a helper can live with the topic that owns it and still be +// used by a neighbouring topic, which keeps each test file readable. +pub(crate) use entries::*; +pub(crate) use helpers::*; +pub(crate) use sync_kdf::*; diff --git a/crates/ffi/src/tests/recycle.rs b/crates/ffi/src/tests/recycle.rs new file mode 100644 index 0000000..b25259c --- /dev/null +++ b/crates/ffi/src/tests/recycle.rs @@ -0,0 +1,213 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Recycle-bin and tombstone semantics for entries and groups. + +use super::*; + +#[test] +pub(crate) fn deleting_an_entry_creates_and_uses_the_recycle_bin() { + let options = CString::new(r#"{"password":"recycle-pass","name":"recycle"}"#).unwrap(); + let mut saved = std::ptr::null_mut(); + let mut saved_len = 0usize; + assert_eq!( + kp_create_database(options.as_ptr(), &mut saved, &mut saved_len), + 0 + ); + let bytes = unsafe { std::slice::from_raw_parts(saved, saved_len) }.to_vec(); + kp_buffer_free(saved, saved_len); + let handle = open_bytes(&bytes, "recycle-pass"); + + let groups: Value = + serde_json::from_str(&call(handle, r#"{"command":"list_groups"}"#)).unwrap(); + let root = groups[0]["uuid"].as_str().unwrap(); + let uuid = create_entry_in(handle, root, r#"{"Title":"delete-me","Password":"p"}"#); + let deleted: Value = serde_json::from_str(&call( + handle, + &format!(r#"{{"command":"delete_entry","uuid":"{uuid}"}}"#), + )) + .unwrap(); + assert_eq!(deleted["recycled"], true); + + let groups: Value = + serde_json::from_str(&call(handle, r#"{"command":"list_groups"}"#)).unwrap(); + let recycle = groups + .as_array() + .unwrap() + .iter() + .find(|group| group["name"] == "Recycle Bin") + .expect("a recycle-bin group must be created"); + let recycle_uuid = recycle["uuid"].as_str().unwrap(); + let entries: Value = serde_json::from_str(&call( + handle, + &format!( + r#"{{"command":"list_entries","group_uuid":"{recycle_uuid}","include_subgroups":true}}"# + ), + )) + .unwrap(); + assert!( + entries + .as_array() + .unwrap() + .iter() + .any(|entry| entry["uuid"] == uuid.as_str()), + "the deleted entry must live in the recycle bin" + ); + assert_eq!(kp_close(handle), 0); +} + +#[test] +pub(crate) fn permanent_entry_deletion_still_uses_a_tombstone() { + let handle = open_fixture(); + let groups: Value = + serde_json::from_str(&call(handle, r#"{"command":"list_groups"}"#)).unwrap(); + let root = groups[0]["uuid"].as_str().unwrap(); + let uuid = create_entry_in(handle, root, r#"{"Title":"gone","Password":"p"}"#); + let deleted: Value = serde_json::from_str(&call( + handle, + &format!(r#"{{"command":"delete_entry","uuid":"{uuid}","permanent":true}}"#), + )) + .unwrap(); + assert_eq!(deleted["recycled"], false); + let full = call_error( + handle, + &format!(r#"{{"command":"get_entry","uuid":"{uuid}"}}"#), + ); + assert!(full.contains("NotFound"), "unexpected error: {full}"); + assert_eq!(kp_close(handle), 0); +} + +#[test] +pub(crate) fn deleting_a_group_recycles_the_whole_subtree() { + let handle = open_fixture(); + let groups: Value = + serde_json::from_str(&call(handle, r#"{"command":"list_groups"}"#)).unwrap(); + let root = groups[0]["uuid"].as_str().unwrap(); + let created: Value = serde_json::from_str(&call( + handle, + &format!(r#"{{"command":"create_group","parent_uuid":"{root}","name":"team"}}"#), + )) + .unwrap(); + let group_uuid = created["uuid"].as_str().unwrap(); + let entry_uuid = create_entry_in(handle, group_uuid, r#"{"Title":"inside","Password":"p"}"#); + + let deleted: Value = serde_json::from_str(&call( + handle, + &format!(r#"{{"command":"delete_group","uuid":"{group_uuid}"}}"#), + )) + .unwrap(); + assert_eq!(deleted["recycled"], true); + + let groups: Value = + serde_json::from_str(&call(handle, r#"{"command":"list_groups"}"#)).unwrap(); + let recycle = groups + .as_array() + .unwrap() + .iter() + .find(|group| group["name"] == "Recycle Bin") + .expect("a recycle-bin group must be created"); + let recycle_uuid = recycle["uuid"].as_str().unwrap(); + let recycled = groups + .as_array() + .unwrap() + .iter() + .find(|group| group["name"] == "team") + .expect("the deleted group must still exist"); + assert_eq!(recycled["parent_uuid"].as_str(), Some(recycle_uuid)); + let recycled_uuid = recycled["uuid"].as_str().unwrap(); + let entries: Value = serde_json::from_str(&call( + handle, + &format!( + r#"{{"command":"list_entries","group_uuid":"{recycled_uuid}","include_subgroups":true}}"# + ), + )) + .unwrap(); + assert!(entries + .as_array() + .unwrap() + .iter() + .any(|entry| entry["uuid"] == entry_uuid.as_str())); + assert_eq!(kp_close(handle), 0); +} + +#[test] +pub(crate) fn permanent_group_deletion_removes_the_subtree() { + let handle = open_fixture(); + let groups: Value = + serde_json::from_str(&call(handle, r#"{"command":"list_groups"}"#)).unwrap(); + let root = groups[0]["uuid"].as_str().unwrap(); + let created: Value = serde_json::from_str(&call( + handle, + &format!(r#"{{"command":"create_group","parent_uuid":"{root}","name":"gone"}}"#), + )) + .unwrap(); + let group_uuid = created["uuid"].as_str().unwrap(); + let entry_uuid = create_entry_in(handle, group_uuid, r#"{"Title":"gone","Password":"p"}"#); + let deleted: Value = serde_json::from_str(&call( + handle, + &format!(r#"{{"command":"delete_group","uuid":"{group_uuid}","permanent":true}}"#), + )) + .unwrap(); + assert_eq!(deleted["recycled"], false); + let error = call_error( + handle, + &format!(r#"{{"command":"get_entry","uuid":"{entry_uuid}"}}"#), + ); + assert!(error.contains("NotFound"), "unexpected error: {error}"); + assert_eq!(kp_close(handle), 0); +} + +#[test] +pub(crate) fn recycled_group_stays_in_the_recycle_bin_through_a_merge() { + let handle = open_fixture(); + let groups: Value = + serde_json::from_str(&call(handle, r#"{"command":"list_groups"}"#)).unwrap(); + let root = groups[0]["uuid"].as_str().unwrap(); + let created: Value = serde_json::from_str(&call( + handle, + &format!(r#"{{"command":"create_group","parent_uuid":"{root}","name":"merge-team"}}"#), + )) + .unwrap(); + let group_uuid: Uuid = created["uuid"].as_str().unwrap().parse().unwrap(); + let entry_uuid = create_entry_in( + handle, + created["uuid"].as_str().unwrap(), + r#"{"Title":"merged-inside","Password":"p"}"#, + ); + let entry_uuid: Uuid = entry_uuid.parse().unwrap(); + + // The remote copy still has the group at its original place; the local + // copy moved it into the recycle bin. A merge must keep the newer + // location instead of resurrecting the old parent. + let remote = save_to_vec(handle); + let deleted: Value = serde_json::from_str(&call( + handle, + &format!( + r#"{{"command":"delete_group","uuid":"{}"}}"#, + group_uuid.to_hex() + ), + )) + .unwrap(); + assert_eq!(deleted["recycled"], true); + + let merged = sync_merge_to_vec(handle, &remote); + let database = keepassity_core::kdbx::reader::parse(&merged, "demopass").expect("merged reads"); + let recycle_uuid = database + .meta + .recycle_bin_uuid + .expect("merged database keeps a recycle bin"); + let recycle = find_group(&database, recycle_uuid).expect("recycle bin exists"); + assert!( + recycle.groups.iter().any(|group| group.uuid == group_uuid), + "the deleted group must stay under the recycle bin" + ); + let (entry, parent) = find_entry(&database, entry_uuid).expect("entry survives merge"); + assert_eq!( + entry + .strings + .iter() + .find(|field| field.key == "Title") + .map(|field| field.value.as_str()), + Some("merged-inside") + ); + assert_eq!(parent, group_uuid); + assert_eq!(kp_close(handle), 0); +} diff --git a/crates/ffi/src/tests/surface.rs b/crates/ffi/src/tests/surface.rs new file mode 100644 index 0000000..becadfd --- /dev/null +++ b/crates/ffi/src/tests/surface.rs @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! The C ABI surface itself: open, version, list, save, error handling. + +use super::*; + +#[test] +pub(crate) fn error_json_is_sanitized_and_cleared() { + let opts = CString::new(r#"{"password":"wrong"}"#).unwrap(); + let bytes = fixture(); + let handle = kp_open(bytes.as_ptr(), bytes.len(), opts.as_ptr()); + assert!(handle.is_null()); + let error = unsafe { CStr::from_ptr(kp_last_error_json()) } + .to_str() + .unwrap(); + assert!(error.contains("BadPassword")); + assert!(!error.contains("wrong")); + assert!(!error.contains("demopass")); +} + +#[test] +pub(crate) fn open_version_list_save_and_diagnose() { + let handle = open_fixture(); + let version: Value = serde_json::from_str(&call(handle, r#"{"command":"version"}"#)).unwrap(); + assert_eq!(version["api"], 1); + let groups: Value = + serde_json::from_str(&call(handle, r#"{"command":"list_groups"}"#)).unwrap(); + assert!(groups.as_array().is_some_and(|groups| !groups.is_empty())); + let entries: Value = + serde_json::from_str(&call(handle, r#"{"command":"list_entries"}"#)).unwrap(); + assert!(entries + .as_array() + .is_some_and(|entries| !entries.is_empty())); + let diagnose: Value = serde_json::from_str(&call(handle, r#"{"command":"diagnose"}"#)).unwrap(); + assert!(diagnose["entries"].as_u64().unwrap() > 0); + + let mut saved = std::ptr::null_mut(); + let mut saved_len = 0usize; + assert_eq!(kp_save(handle, &mut saved, &mut saved_len), 0); + assert!(!saved.is_null() && saved_len > 0); + let verify_opts = CString::new(r#"{"password":"demopass"}"#).unwrap(); + assert_eq!(kp_verify(saved, saved_len, verify_opts.as_ptr()), 0); + kp_buffer_free(saved, saved_len); + assert_eq!(kp_close(handle), 0); +} + +#[test] +pub(crate) fn null_and_locked_paths_do_not_panic() { + assert_ne!(kp_close(std::ptr::null_mut()), 0); + assert_ne!(kp_lock(std::ptr::null_mut()), 0); + let handle = open_fixture(); + assert_eq!(kp_lock(handle), 0); + let command = CString::new(r#"{"command":"list_entries"}"#).unwrap(); + let mut output = std::ptr::null_mut(); + assert_ne!(kp_call(handle, command.as_ptr(), &mut output), 0); + assert_eq!(kp_close(handle), 0); +} + +#[test] +pub(crate) fn crud_and_totp_commands_smoke() { + let handle = open_fixture(); + let groups: Value = + serde_json::from_str(&call(handle, r#"{"command":"list_groups"}"#)).unwrap(); + let group_uuid = groups[0]["uuid"].as_str().unwrap().to_string(); + let create = format!( + r#"{{"command":"create_entry","group_uuid":"{}","fields":{{"Title":"ffi-created","UserName":"u","Password":"p"}}}}"#, + group_uuid + ); + let created: Value = serde_json::from_str(&call(handle, &create)).unwrap(); + let entry_uuid = created["uuid"].as_str().unwrap().to_string(); + let get = format!(r#"{{"command":"get_entry","uuid":"{}"}}"#, entry_uuid); + let full: Value = serde_json::from_str(&call(handle, &get)).unwrap(); + assert_eq!(full["title"], "ffi-created"); + let update = format!( + r#"{{"command":"update_entry","uuid":"{}","patch":{{"Title":"ffi-updated"}}}}"#, + entry_uuid + ); + let _: Value = serde_json::from_str(&call(handle, &update)).unwrap(); + let set_totp = format!( + r#"{{"command":"totp_set","uuid":"{}","config":{{"secret_base32":"JBSWY3DPEHPK3PXP","algorithm":"SHA1","digits":6,"period":30,"encoder":"totp"}}}}"#, + entry_uuid + ); + let _: Value = serde_json::from_str(&call(handle, &set_totp)).unwrap(); + let code = format!( + r#"{{"command":"totp_code","uuid":"{}","at_unix":0}}"#, + entry_uuid + ); + let code: Value = serde_json::from_str(&call(handle, &code)).unwrap(); + assert_eq!(code["code"].as_str().unwrap().len(), 6); + let delete_totp = format!(r#"{{"command":"totp_delete","uuid":"{}"}}"#, entry_uuid); + let _: Value = serde_json::from_str(&call(handle, &delete_totp)).unwrap(); + let delete = format!( + r#"{{"command":"delete_entry","uuid":"{}","permanent":true}}"#, + entry_uuid + ); + let _: Value = serde_json::from_str(&call(handle, &delete)).unwrap(); + assert_eq!(kp_close(handle), 0); +} diff --git a/crates/ffi/src/tests/sync_kdf.rs b/crates/ffi/src/tests/sync_kdf.rs new file mode 100644 index 0000000..7396599 --- /dev/null +++ b/crates/ffi/src/tests/sync_kdf.rs @@ -0,0 +1,244 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Sync merge/commit, save fidelity, KDF and database settings. + +use super::*; + +pub(crate) fn sync_merge_to_vec(handle: *mut KpHandle, remote: &[u8]) -> Vec { + let mut bytes = std::ptr::null_mut(); + let mut len = 0usize; + let mut conflicts = std::ptr::null_mut(); + assert_eq!( + kp_sync_merge( + handle, + remote.as_ptr(), + remote.len(), + &mut bytes, + &mut len, + &mut conflicts + ), + 0 + ); + if !conflicts.is_null() { + kp_string_free(conflicts); + } + let copy = unsafe { std::slice::from_raw_parts(bytes, len) }.to_vec(); + kp_buffer_free(bytes, len); + copy +} + +#[test] +pub(crate) fn save_keeps_the_source_kdbx_header() { + let direct = keepassity_core::kdbx::reader::parse(&fixture(), "demopass").unwrap(); + let source_version = direct.format_version.clone(); + let handle = open_fixture(); + let mut bytes = std::ptr::null_mut(); + let mut len = 0usize; + assert_eq!(kp_save(handle, &mut bytes, &mut len), 0); + let saved = unsafe { std::slice::from_raw_parts(bytes, len) }; + let database = + keepassity_core::kdbx::reader::parse(saved, "demopass").expect("saved file reads"); + let header = database.outer.expect("saved file keeps its header"); + let version = header.version.clone(); + let kdf = header.kdf.clone(); + assert_eq!(version, source_version, "kdf={kdf:?}"); + assert!( + matches!( + header.kdf, + Some(keepassity_core::model::KdfSettings::Aes { .. }) + ), + "the AES-KDF fixture must not be rewritten as Argon2id" + ); + kp_buffer_free(bytes, len); + assert_eq!(kp_close(handle), 0); +} + +#[test] +pub(crate) fn repeated_saves_reuse_the_cached_kdf_and_stay_readable() { + let handle = open_fixture(); + let first = save_to_vec(handle); + let second = save_to_vec(handle); + assert_ne!( + first, second, + "a save must still use a fresh master seed/IV" + ); + keepassity_core::kdbx::reader::parse(&first, "demopass").expect("first save reads"); + keepassity_core::kdbx::reader::parse(&second, "demopass").expect("second save reads"); + assert_eq!(kp_close(handle), 0); +} + +pub(crate) fn save_to_vec(handle: *mut KpHandle) -> Vec { + let mut bytes = std::ptr::null_mut(); + let mut len = 0usize; + assert_eq!(kp_save(handle, &mut bytes, &mut len), 0); + let copy = unsafe { std::slice::from_raw_parts(bytes, len) }.to_vec(); + kp_buffer_free(bytes, len); + copy +} + +#[test] +pub(crate) fn api_version_matches_core() { + assert_eq!(kp_api_version(), keepassity_core::API_MAJOR); +} + +#[test] +pub(crate) fn sync_commit_rejects_an_incomplete_baseline() { + let handle = open_fixture(); + // A null/null commit used to succeed and clear the dirty flag, which let + // the next sync overwrite local edits without a baseline. + assert_ne!( + kp_sync_commit(handle, std::ptr::null(), std::ptr::null()), + 0 + ); + let empty_etag = CString::new("").unwrap(); + assert_ne!( + kp_sync_commit(handle, empty_etag.as_ptr(), std::ptr::null()), + 0 + ); + let short_sha = CString::new("abc").unwrap(); + assert_ne!( + kp_sync_commit(handle, std::ptr::null(), short_sha.as_ptr()), + 0 + ); + let valid_sha = CString::new("a".repeat(64)).unwrap(); + assert_eq!( + kp_sync_commit(handle, std::ptr::null(), valid_sha.as_ptr()), + 0 + ); + assert_eq!(kp_close(handle), 0); +} + +pub(crate) fn header_kdf(bytes: &[u8]) -> keepassity_core::model::KdfSettings { + keepassity_core::kdbx::reader::parse(bytes, "demopass") + .expect("the saved database reads") + .outer + .expect("KDBX 4 header") + .kdf + .expect("header carries a KDF") +} + +#[test] +pub(crate) fn database_info_reports_the_kdf_the_file_carries() { + let handle = open_fixture(); + let info = parse(&call(handle, r#"{"command":"database_info"}"#)); + assert!( + info["format_version"] == "4.0" || info["format_version"] == "4.1", + "unexpected version: {}", + info["format_version"] + ); + assert_eq!(info["kdf"]["type"], "aes-kdf"); + assert_eq!(info["kdf"]["mobile_safe"], true); + assert_eq!(kp_close(handle), 0); +} + +#[test] +pub(crate) fn set_kdf_reaches_the_saved_header_even_after_a_cached_save() { + let handle = open_fixture(); + // The first save fills the KDF cache with the source parameters; the + // backend would reuse them for the next save unless set_kdf drops them. + let before = save_to_vec(handle); + let info = parse(&call( + handle, + r#"{"command":"set_kdf","preset":"keepassxc"}"#, + )); + assert_eq!(info["kdf"]["type"], "argon2id"); + assert_eq!(info["kdf"]["memory_mib"], 64); + + let after = save_to_vec(handle); + match header_kdf(&after) { + keepassity_core::model::KdfSettings::Argon2 { + memory_kib, + iterations, + .. + } => { + assert_eq!(memory_kib, 64 * 1024); + assert_eq!(iterations, 3); + } + other => panic!("expected the requested Argon2id, got {other:?}"), + } + assert!( + matches!( + header_kdf(&before), + keepassity_core::model::KdfSettings::Aes { .. } + ), + "the first save must still carry the source KDF" + ); + assert_eq!(kp_close(handle), 0); +} + +#[test] +pub(crate) fn set_kdf_accepts_exact_values() { + let handle = open_fixture(); + // The desktop app restores an earlier copy's parameters by sending the + // values it read back, so the exact-object shape is part of the contract. + let info = parse(&call( + handle, + r#"{"command":"set_kdf","kdf":{"type":"argon2id","memory_mib":32,"iterations":2,"parallelism":2,"rounds":0}}"#, + )); + assert_eq!(info["kdf"]["memory_mib"], 32); + assert_eq!(info["kdf"]["iterations"], 2); + + let saved = save_to_vec(handle); + match header_kdf(&saved) { + keepassity_core::model::KdfSettings::Argon2 { + memory_kib, + iterations, + parallelism, + .. + } => { + assert_eq!(memory_kib, 32 * 1024); + assert_eq!(iterations, 2); + assert_eq!(parallelism, 2); + } + other => panic!("expected the exact Argon2 settings, got {other:?}"), + } + assert_eq!(kp_close(handle), 0); +} + +#[test] +pub(crate) fn set_database_settings_rejects_an_out_of_range_history() { + let handle = open_fixture(); + let error = call_error( + handle, + r#"{"command":"set_database_settings","history_max_items":100000}"#, + ); + assert!(error.contains("history_max_items"), "unexpected: {error}"); + assert_eq!(kp_close(handle), 0); +} + +#[test] +pub(crate) fn database_info_reports_identity_and_settings_round_trip() { + let handle = open_fixture(); + let info = parse(&call(handle, r#"{"command":"database_info"}"#)); + assert_eq!( + info["vault_uuid"].as_str().map(str::len), + Some(32), + "the root-group UUID identifies the database" + ); + let before = parse(&call(handle, r#"{"command":"database_settings"}"#)); + assert!(before["history_max_items"].is_number()); + + let changed = parse(&call( + handle, + r#"{"command":"set_database_settings","recycle_bin_enabled":false,"history_max_items":25}"#, + )); + assert_eq!(changed["recycle_bin_enabled"], false); + assert_eq!(changed["history_max_items"], 25); + + let saved = save_to_vec(handle); + let reopened = + keepassity_core::kdbx::reader::parse(&saved, "demopass").expect("the saved database opens"); + assert!(!reopened.meta.recycle_bin_enabled); + assert_eq!(reopened.meta.history_max_items, 25); + assert_eq!(kp_close(handle), 0); +} + +#[test] +pub(crate) fn set_kdf_rejects_extreme_custom_parameters() { + let handle = open_fixture(); + let error = call_error( + handle, + r#"{"command":"set_kdf","kdf":{"type":"argon2id","memory_mib":4096,"iterations":1,"parallelism":1}}"#, + ); + assert!(error.contains("Argon2 memory"), "unexpected error: {error}"); + assert_eq!(kp_close(handle), 0); +} diff --git a/crates/ffi/src/tests/totp_password.rs b/crates/ffi/src/tests/totp_password.rs new file mode 100644 index 0000000..1794645 --- /dev/null +++ b/crates/ffi/src/tests/totp_password.rs @@ -0,0 +1,169 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! TOTP code generation and password generation. + +use super::*; + +#[test] +pub(crate) fn password_generate_honours_options_and_reports_consistent_entropy() { + let handle = open_fixture(); + + // Lowercase + digits without ambiguous look-alikes: 24 + 8 = 32 + // symbols, i.e. exactly 5 bits per character -> 160 bits for 32 chars. + let generated = parse(&call( + handle, + r#"{"command":"password_generate","length":32,"classes":{"lowercase":true,"uppercase":false,"digits":true,"symbols":false},"exclude_ambiguous":true}"#, + )); + let password = generated["password"].as_str().expect("password string"); + assert_eq!(password.chars().count(), 32); + assert!(password + .chars() + .all(|character| character.is_ascii_lowercase() || character.is_ascii_digit())); + assert!( + password + .chars() + .all(|character| !"Il1O0o".contains(character)), + "ambiguous characters must be excluded: {password}" + ); + assert_eq!(generated["entropy_bits"].as_f64(), Some(160.0)); + + // Digits only, ambiguous excluded: "23456789" -> 3 bits per char. + let digits_only = parse(&call( + handle, + r#"{"command":"password_generate","length":16,"classes":{"lowercase":false,"uppercase":false,"digits":true,"symbols":false},"exclude_ambiguous":true}"#, + )); + let password = digits_only["password"].as_str().expect("password string"); + assert_eq!(password.len(), 16); + assert!(password + .chars() + .all(|character| ('2'..='9').contains(&character))); + assert_eq!(digits_only["entropy_bits"].as_f64(), Some(48.0)); + + // The same digits-only charset without the exclusion has 10 symbols; + // entropy must grow accordingly (10 * log2(10) for 10 characters). + let digits_without_exclusion = parse(&call( + handle, + r#"{"command":"password_generate","length":10,"classes":{"lowercase":false,"uppercase":false,"digits":true,"symbols":false},"exclude_ambiguous":false}"#, + )); + let password = digits_without_exclusion["password"] + .as_str() + .expect("password string"); + assert_eq!(password.len(), 10); + assert!(password.chars().all(|character| character.is_ascii_digit())); + let expected = 10.0 * 10.0_f64.log2(); + assert_eq!( + digits_without_exclusion["entropy_bits"].as_f64(), + Some(expected) + ); + assert_ne!( + digits_only["entropy_bits"].as_f64(), + digits_without_exclusion["entropy_bits"].as_f64() + ); + + // All classes enabled: 26 lower + 26 upper + 10 digits + 24 symbols = 86. + let everything = parse(&call( + handle, + r#"{"command":"password_generate","length":12,"classes":{"lowercase":true,"uppercase":true,"digits":true,"symbols":true},"exclude_ambiguous":false}"#, + )); + assert_eq!(everything["password"].as_str().unwrap().chars().count(), 12); + let expected = 12.0 * 86.0_f64.log2(); + assert_eq!(everything["entropy_bits"].as_f64(), Some(expected)); + + // No character class selected must be rejected, not silently generated. + let error = call_error( + handle, + r#"{"command":"password_generate","length":8,"classes":{"lowercase":false,"uppercase":false,"digits":false,"symbols":false}}"#, + ); + assert!( + error.contains("InvalidArgument"), + "unexpected error: {error}" + ); + assert!( + error.contains("charset is empty"), + "unexpected error: {error}" + ); + + assert_eq!(kp_close(handle), 0); +} + +#[test] +pub(crate) fn totp_code_at_unix_uses_the_requested_window() { + let bytes = fixture_bytes("test_db_kdbx4_with_totp_entry.kdbx"); + let handle = open_bytes(&bytes, "test"); + + let entries = parse(&call(handle, r#"{"command":"list_entries"}"#)); + let uuid = entries + .as_array() + .expect("entry list") + .iter() + .find(|entry| entry["has_totp"].as_bool() == Some(true)) + .and_then(|entry| entry["uuid"].as_str()) + .expect("fixture has a TOTP entry") + .to_string(); + let full = parse(&call( + handle, + &format!(r#"{{"command":"get_entry","uuid":"{uuid}"}}"#), + )); + assert_eq!(full["title"].as_str(), Some("this entry has totp")); + let config = &full["totp"]; + // Public fixture configuration: otpauth://totp/KeePassXC:none + // ?secret=JBSWY3DPEHPK3PXP&period=30&digits=6 (SHA-1). + assert_eq!(config["secret_base32"].as_str(), Some("JBSWY3DPEHPK3PXP")); + assert_eq!(config["algorithm"].as_str(), Some("SHA1")); + assert_eq!(config["digits"].as_u64(), Some(6)); + assert_eq!(config["period"].as_u64(), Some(30)); + + // Reference codes for RFC 6238 TOTP-SHA1 / 6 digits / 30 s with the + // fixture secret, computed by an independent implementation: + // (at_unix, code, seconds remaining in the window). + let cases: [(u64, &str, u64); 8] = [ + (0, "282760", 30), + (29, "282760", 1), + (30, "996554", 30), + (59, "996554", 1), + (1_700_000_000, "324550", 10), + (1_700_000_009, "324550", 1), + (1_700_000_010, "367665", 30), + (1_700_000_040, "870960", 30), + ]; + for (at_unix, expected_code, expected_remaining) in cases { + let code = parse(&call( + handle, + &format!(r#"{{"command":"totp_code","uuid":"{uuid}","at_unix":{at_unix}}}"#), + )); + assert_eq!( + code["code"].as_str(), + Some(expected_code), + "code at at_unix={at_unix}" + ); + assert_eq!( + code["remaining"].as_u64(), + Some(expected_remaining), + "remaining at at_unix={at_unix}" + ); + assert_eq!(code["period"].as_u64(), Some(30)); + assert_eq!(code["digits"].as_u64(), Some(6)); + assert_eq!(code["algorithm"].as_str(), Some("SHA1")); + assert_eq!(code["skew_warning"].as_bool(), Some(false)); + } + + // Same window keeps the code stable, a step boundary rotates it. + let window_start = parse(&call( + handle, + &format!(r#"{{"command":"totp_code","uuid":"{uuid}","at_unix":0}}"#), + )); + let window_end = parse(&call( + handle, + &format!(r#"{{"command":"totp_code","uuid":"{uuid}","at_unix":29}}"#), + )); + let next_window = parse(&call( + handle, + &format!(r#"{{"command":"totp_code","uuid":"{uuid}","at_unix":30}}"#), + )); + assert_eq!(window_start["code"], window_end["code"]); + assert_ne!(window_start["code"], next_window["code"]); + assert_eq!(window_start["remaining"].as_u64(), Some(30)); + assert_eq!(window_end["remaining"].as_u64(), Some(1)); + assert_eq!(next_window["remaining"].as_u64(), Some(30)); + + assert_eq!(kp_close(handle), 0); +} diff --git a/crates/ffi/src/totp_helpers.rs b/crates/ffi/src/totp_helpers.rs new file mode 100644 index 0000000..e3cfeac --- /dev/null +++ b/crates/ffi/src/totp_helpers.rs @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! TOTP conversions between the core spec and the wire DTO. + +use super::*; + +pub(crate) fn algorithm_name(algorithm: CoreTotpAlgorithm) -> &'static str { + match algorithm { + CoreTotpAlgorithm::Sha1 => "SHA1", + CoreTotpAlgorithm::Sha256 => "SHA256", + CoreTotpAlgorithm::Sha512 => "SHA512", + } +} + +pub(crate) fn core_totp_to_dto(spec: &totp_fields::TotpSpec) -> DtoTotpConfig { + let config = &spec.config; + DtoTotpConfig { + secret_base32: base32_encode(&config.secret), + issuer: spec.issuer.clone(), + account: spec.account.clone(), + algorithm: match config.algorithm { + CoreTotpAlgorithm::Sha1 => DtoTotpAlgorithm::Sha1, + CoreTotpAlgorithm::Sha256 => DtoTotpAlgorithm::Sha256, + CoreTotpAlgorithm::Sha512 => DtoTotpAlgorithm::Sha512, + }, + digits: config.digits, + period: config.period, + encoder: match config.encoder { + CoreTotpEncoder::Totp => DtoTotpEncoder::Totp, + CoreTotpEncoder::Steam => DtoTotpEncoder::Steam, + }, + counter: None, + } +} + +pub(crate) fn dto_to_totp_spec(value: &Value) -> Result { + let secret = value + .get("secret_base32") + .and_then(Value::as_str) + .ok_or_else(|| FfiError::invalid("secret_base32 is required"))?; + let secret_bytes = + base32_decode(secret).map_err(|error| FfiError::invalid(error.to_string()))?; + let algorithm = match value + .get("algorithm") + .and_then(Value::as_str) + .unwrap_or("SHA1") + { + "SHA256" => CoreTotpAlgorithm::Sha256, + "SHA512" => CoreTotpAlgorithm::Sha512, + _ => CoreTotpAlgorithm::Sha1, + }; + let encoder = match value + .get("encoder") + .and_then(Value::as_str) + .unwrap_or("totp") + { + "steam" => CoreTotpEncoder::Steam, + _ => CoreTotpEncoder::Totp, + }; + let config = CoreTotpConfig { + secret: secret_bytes, + algorithm, + digits: value + .get("digits") + .and_then(Value::as_u64) + .unwrap_or(6) + .clamp(1, 10) as u32, + period: value + .get("period") + .and_then(Value::as_u64) + .unwrap_or(30) + .clamp(1, 3_600) as u32, + encoder, + }; + Ok(totp_fields::TotpSpec { + config, + issuer: value + .get("issuer") + .and_then(Value::as_str) + .map(str::to_string), + account: value + .get("account") + .and_then(Value::as_str) + .map(str::to_string), + }) +} diff --git a/docs/architecture.md b/docs/architecture.md index 660bb55..dc596a4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -8,13 +8,16 @@ planned for v1.x and is expected to consume the same core directly. ``` ┌─────────────────────────────────────────────────────────────┐ -│ shell (apps/windows) │ -│ UI, dialogs, platform adapters: DPAPI, tray, clipboard, │ -│ idle/lock detection, file pickers │ +│ shell (apps/windows/Keepassity.App) │ +│ views/XAML, platform adapters: DPAPI, tray, clipboard, │ +│ idle/lock detection, file pickers, window lifetime │ +├─────────────────────────────────────────────────────────────┤ +│ view models (apps/windows/Keepassity.ViewModels) │ +│ presentation state and commands; no WinUI types; tested │ +│ headless with fake core/text ports (ADR-0032) │ ├─────────────────────────────────────────────────────────────┤ │ application services (apps/windows/Keepassity.Core) │ -│ settings, sync state, WebDAV client, backups, sync │ -│ orchestration/conflict flow │ +│ settings, sync state, WebDAV client, backups, app paths │ ├─────────────────────────────────────────────────────────────┤ │ FFI contract (crates/ffi) │ │ C ABI + JSON commands; the only cross-language boundary │ @@ -34,15 +37,106 @@ planned for v1.x and is expected to consume the same core directly. - **The WinUI project owns platform integration.** It creates windows and dialogs, hosts the tray icon, clears the clipboard and stores credentials with DPAPI. File and WebDAV IO goes through the application-services layer; `crates/core` stays pure. +- **The presentation layer is MVVM.** `Keepassity.ViewModels` holds observable state and + commands and depends on `ICoreClient` plus injected platform ports; it must not reference + WinUI. Views bind with `x:Bind` and keep only view mechanics (focus, pickers, window + lifetime). `CommunityToolkit.Mvvm` is the source-generator baseline (ADR-0032). - **Application services live in `apps/windows/Keepassity.Core`.** Settings, sync state, the - WebDAV client, backups and sync orchestration are already platform-neutral C# and covered + WebDAV client, backups, paths and the `ICoreClient` port are platform-neutral C# and covered by the headless `tests/app-core` suite, so the future Linux shell can reuse them instead of - duplicating the logic. + duplicating the logic. The WinUI shell also carries the FFI adapter (`CoreClient`). +- **The sync protocol is an application service.** `SyncCoordinator` runs one WebDAV sync + (decide → upload with back-off → download → three-way merge → conflict choice → baseline + commit) against three narrow ports: `ISyncRemote` (implemented by `WebDavClient`), + `IVaultDocument` (the open window: durable write, reopen, merge through a second core handle) + and the expanded `ICoreClient`. The window keeps only the connection, the conflict dialog and + the toasts. This is the part of the sync path where ordering decides whether data survives a + crash, so it is tested headlessly with fakes (`SyncCoordinatorTests`) instead of living in the + 6k-line window. The coordinator records the local file hash for the run (updated whenever it + writes the file itself) and checks it before every replace and before writing an upload + snapshot; when the file changed in the meantime a save during a download, merge or upload is + merged later instead of being undone. Conflict copies are named from the local and remote + content hashes, so an unresolved pair is reused across syncs and restarts instead of accumulating + timestamped duplicates in the vault folder. `WebDavClient` applies per-request timeouts: 45 s for + the small PROPFIND metadata call and 30 minutes for a whole-file download or upload, so a large + vault on a slow link is not cut off while a stalled transfer still ends with a clear timeout. + An unreadable remote copy never replaces the local vault: the run pauses with the local file + untouched, and only an explicit user confirmation replaces the remote with the verified local + copy (the sync coordinator's one-shot `OverwriteUnreadableRemote` option). The unreadable bytes + are first preserved next to the local database under a hash-derived name, so the repair never + destroys the only copy of a valid database that happens to use another master password. Before + an upload is reported as successful, its stored size is read back with a PROPFIND; a server that + answered 2xx but kept fewer bytes raises an incomplete-upload error instead of becoming the + baseline. ## Data safety -- Saves use a temp file, a timestamped backup and a verified atomic replace; the save - protocol is exercised by the core save/sync tests. +- Saves are verified and durable in two layers: `kp_save` decrypts and parses the fresh + ciphertext with the cached KDF key before returning it, then `AtomicFile` writes a + `.keepassity-tmp-` sibling with write-through and an explicit flush, keeps a + timestamped backup and replaces the live file atomically. The same temp infix is used by the + core's IO-free `save_atomic` protocol; an unlock removes leftover temps before opening. The + Windows path therefore matches the core protocol's ordering (verify → temp → backup → replace), + with the backup hook delegated to `BackupService`. The final placement uses `File.Replace` + (metadata errors ignored) and falls back to a same-volume rename on volumes without that + primitive (FAT/exFAT, some network shares); both are renames, so a crash still leaves the old or + new complete file, and the backup taken just before is the recovery point. The placement is + guarded at the last moment (after the backup, immediately before the rename): a database changed + outside the application aborts the write with `VaultChanged`, so the newer external file is never + overwritten. +- A damaged database can be replaced from the unlock screen by the newest local backup that the + entered master password opens (`VaultRecovery`); the damaged file is kept as a before-restore + backup, and the normal in-app restore list still requires the restored vault to be open. +- A run marker (`RunStateStore`) separates a clean close from a crash or power loss: the next + launch reports an unclean previous session on the unlock surface and points at the backups. The + marker is written atomically, is best effort, and ignores a concurrent test-only second window. +- The local WebDAV cache is bounded by a startup cleanup (`RemoteCacheCleaner`): clean working + copies untouched for ninety days are dropped (a remote re-open downloads them again), along with + backups/metadata/sync state whose working copy vanished. Dirty copies, hash-mismatched copies, + unknown-provenance copies and the current target are kept; a deleted copy is also forgotten by + the recent-databases list. The pass runs only while this process owns the single-instance mutex, + before any window can open a cache file. +- Diagnostics archives are written through the flushed-temporary/rename protocol, exported names + are unique even within one millisecond, only the newest ten are kept, and the archive never + contains database paths, WebDAV URLs or usernames. +- Crash residue is bounded too: opening a vault removes crash-left save, restore and backup + temporaries next to it, and the first launch removes stale protocol temporaries across the + application data folder. Both passes use age thresholds and only touch files whose names carry + the protocol infixes, so an active write is never disturbed. +- Logs are bounded: a day file rotates to one `.1` sibling at 5 MB, pruning enforces the + fourteen-day window and a 50 MB folder ceiling, and all handles share read/write/delete so a + second writer or a diagnostics export never loses a line to a sharing violation. +- A newly created database goes through the same protocol from its first byte: + `AtomicFile.WriteNew` flushes a temporary and performs a create-only move, so it never replaces + a file another program created in the race, and `NewDatabasePreparer` writes a WebDAV working + copy before recording the clean sync baseline. +- Remote downloads are decrypted with the current master password before they replace the + live database; download and upload redirects are rejected rather than followed, and a sync + baseline without a content hash is refused. A corrupt sync sidecar makes the vault dirty + instead of clean. Opening a database from WebDAV uses the same rule: the downloaded bytes are + opened first and only a database that decrypted is promoted to the local working copy + (`RemoteVaultOpener`), so a bad download cannot overwrite the previous copy. +- A sync run only records a clean baseline after the local write, the verified upload and the + core's baseline commit succeeded, in that order: `SyncCoordinator` writes the database first, + uploads second, asks the core to accept the new etag/hash third, and only then saves the + sidecar. A failure at any step leaves the vault dirty, so the next run retries instead of + trusting a half-finished sync. +- One process writes a vault: opening it takes a cross-process lock, and a save compares the + file's SHA-256 with the bytes the in-memory model came from. An external change blocks the + save instead of being overwritten. The lock has two layers: the account-scoped file under the + application data folder, plus (for a writable vault folder) an exclusive `.keepassity/locks` + file next to the database, which also coordinates different Windows accounts or machines + opening the same shared folder; a read-only folder degrades to the account-scoped layer. + `VaultSession` owns those three guards (lock, in-process + write gate, fingerprint) and is the only path for saves, sync replacements and backup + restores, so the window cannot compose them differently per call site. The new ciphertext is + decrypted and parsed with the cached KDF key before it can replace the file; the write gate + serializes save, sync-copy and restore replacements so an older async snapshot cannot land + last. `VaultSession` also reports whether a write is queued or running; the window drains that + work (bounded) before it disposes the session and core on close, and locks the core only after a + running save finished. Sync reads the live database through the same gate (`ReadBytesAsync`), so a + read cannot collide with a replace. A sync that arrives at its local replace phase after the + vault locked is refused instead of replacing the database under a locked core. - The real database, credentials and WebDAV working copies never enter a git repository. - Test fixtures are synthetic or public samples; see `tests/fixtures/README.md`. diff --git a/docs/compatibility.md b/docs/compatibility.md index 36292c1..8f6c551 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -4,11 +4,12 @@ ## KDBX clients -"Files we write" come from two paths: an **app save** writes a KDBX 4.0 file through the -model writer (see KDBX write format below), while the **CLI `rewrite`** used for interop -evidence re-saves through the backend and preserves the input format version. The fixture set -is `tests/fixtures/keepass-rs`: 25 public samples, of which 17 are rewritten and verified -end-to-end, two are broken files that must be rejected, and six key-file / +"Files we write" come from two paths: an **app save** preserves the source KDBX 4 outer +format (version, cipher, compression and KDF settings) through the model writer, while a +KDBX 3.1 source follows the documented upgrade to KDBX 4.0. The **CLI `rewrite`** used for +interop evidence re-saves through the backend and preserves the input format version. The +fixture set is `tests/fixtures/keepass-rs`: 25 public samples, of which 17 are rewritten and +verified end-to-end, two are broken files that must be rejected, and six key-file / challenge-response samples are outside the v1.0 scope. | Client | Can read files we write | We can read files it writes | Version | Status | @@ -22,14 +23,24 @@ trip runs in CI. The database used for the real-vault checks is never committed. ### KDBX write format -App saves are written as **KDBX 4.0** with the backend defaults (AES-256, Argon2id with 128 MiB / 6 iterations / 4 lanes for new databases, ChaCha20 -protected stream, gzip): a database opened as KDBX 3.1 or 4.1 is written back as KDBX 4.0. -The CLI/interop `rewrite` path preserves the input version. Model data that the writer maps -(entries, groups, fields, times, tags, history, attachments, deleted objects, TOTP fields) is -carried through an edit/save; raw XML blocks, custom icons and auto-type data that the model -writer does not map are not preserved by an app save. The app edit/save path was manually -checked at G3 (edit, save, reopen in KeePass 2.x); the interop matrix above covers the backend -rewrite round trip. +App saves preserve the KDBX 4 outer header read from the source file: the format version +(4.0 stays 4.0, 4.1 stays 4.1), outer cipher (AES-128/256, Twofish or ChaCha20), compression, +KDF type and cost (AES-KDF rounds or Argon2 memory/iterations/parallelism) and the +`PublicCustomData` header field. The KDF salt is chosen on the first save and the transformed +key is reused for later saves in the same unlocked session; a fresh master seed, encryption IV +and protected-stream key are still drawn on every save. A newly created database uses the +write defaults (KDBX 4.0, AES-256, Argon2id 64 MiB / 3 iterations / 2 lanes, gzip) chosen to +match the widespread KeePassXC profile, so the file opens on desktop and mobile clients alike; +a stronger 128 MiB / 6 / 4 or 256 MiB / 8 / 4 set is an explicit, desktop-only choice. A KDBX 3.1 +source is upgraded to KDBX 4.0 with those defaults, because KDBX3 has no equivalent outer +header after the upgrade. The KDF of an existing database is only changed through the explicit +"encryption parameters" dialog (or `keepassity-cli kdf --set …`); saving never rewrites it. The +protected-stream algorithm follows the write backend (ChaCha20). +Model data that the writer maps (entries, groups, fields, times, tags, history, attachments, +deleted objects, TOTP fields) is carried through an edit/save; raw XML blocks, custom icons and +auto-type data that the model writer does not map are not preserved by an app save. The app +edit/save path was manually checked at G3 (edit, save, reopen in KeePass 2.x); the interop +matrix above covers the backend rewrite round trip. ## WebDAV TLS and self-signed certificates @@ -108,6 +119,7 @@ opened in KeePass, which lets you re-save it with normal settings. - No auto-update, no MSIX; the installer and portable binaries are unsigned (README notes SmartScreen). - WebDAV: local mock and one real provider (Jianguoyun) tested; other providers are untested. -- The app writes KDBX 4.0 files (see KDBX write format); use KeePass 2.x / KeePassXC to open - them if you need the data in another client. -- The 30-day acceptance (G5) is still pending; `v1.0.0` is not published yet. +- The app preserves KDBX 4 outer format settings on save and upgrades KDBX 3.1 to 4.0 (see + KDBX write format); use KeePass 2.x / KeePassXC to open the files if you need the data in + another client. +- `v1.0.0` was published on 2026-12-01 without the planned 30-day acceptance (owner decision). diff --git a/docs/release.md b/docs/release.md index 69297de..ed3ad3f 100644 --- a/docs/release.md +++ b/docs/release.md @@ -4,12 +4,12 @@ The public repository ships self-contained Windows packages built from a tag. ## Current status -- The source tree is at version **1.0.0**; no `v1.0.0` tag exists yet and no GitHub Release - has been published. -- Publishing is gated by the **30-day real-use acceptance**: the 1.0.0 build is produced for - the acceptance period first, and the `v1.0.0` tag is created only after it passes. -- No GitHub Release exists yet: the obsolete `v0.1.0` draft and tag were removed on - 2026-11-09, and `v1.0.0` is created only after the 30-day acceptance passes. +- Version **1.0.0** was released on **2026-12-01**; the annotated tag `v1.0.0` exists and the + GitHub Release is published. +- The 30-day real-use acceptance had not started when the release was published: the owner + chose to ship the first release directly and keep the acceptance programme for the next + release. +- The obsolete `v0.1.0` draft and tag were removed on 2026-11-09. - Code signing is not configured. Releases ship with SHA-256 checksums and build-provenance attestations only (no Authenticode signature, no MSIX, no auto-update). @@ -24,9 +24,10 @@ The public repository ships self-contained Windows packages built from a tag. - The Inno Setup script (`installer/keepassity.iss`) defaults to `1.0.0`; CI overrides it with the tag value through `scripts/build-installer.ps1 -Version`. -## Build for acceptance (no tag, no publish) +## Build the release locally -Produce the 1.0.0 build and use it for the 30-day acceptance without creating a tag. +Produce the 1.0.0 build locally if you need to reproduce the release artifacts without +creating a tag. The build output must live in a **normal (Medium integrity) folder on disk** if your working directory carries a Low integrity label (some sandboxed setups do): a `setup.exe` @@ -35,7 +36,12 @@ fails even though the build succeeded, and `icacls ... /setintegritylevel Medium relabel it without `SeRelabelPrivilege`. A folder such as `%USERPROFILE%\keepassity-release` works; `out\dist` inside a Low-labeled workspace does not. The four steps below produce the portable folder, the installer, the checksums and the -SBOM, and `tools/installer/verify-install.ps1` checks the result after installing it. +SBOM, and `tools/installer/verify-install.ps1` checks the result after installing it. The +uninstaller only removes files the installer created; a user file placed next to the +executable is kept, and the verification script checks for leftover program files rather than +requiring the folder itself to disappear. `SHA256SUMS` includes the SBOM and is verified again +before the draft release is created; lines use LF so `sha256sum -c` works on non-Windows +machines. The app project's default FFI lookup is `out\cargo-target\release`, which is what `CARGO_TARGET_DIR` below matches. Inno Setup 6 must be installed for the installer step. @@ -54,16 +60,16 @@ powershell -NoProfile -ExecutionPolicy Bypass -File scripts\make-checksums.ps1 ` -Directory "$env:USERPROFILE\Desktop\keepassity-release" ``` -The acceptance build is not uploaded anywhere; it stays local (or in the private process -repository's evidence) until the tag is created. +The local build is not uploaded anywhere; the tag workflow produces the published artifacts. -## Tag and release (after acceptance) +## Tag and release 1. Merge the release branch into `main`. 2. Create an annotated tag `v1.0.0` on `main` and push it; the workflow triggers on `v*` tags. 3. The release workflow (`.github/workflows/release.yml`, Windows runner): - - verifies the source: `cargo test --workspace`, the `tests/app-core` suite and - `scripts/verify-fixtures.ps1`; + - verifies the source: `cargo fmt --all -- --check`, + `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`, + the `tests/app-core` suite, the public-file allowlist and `scripts/verify-fixtures.ps1`; - builds `cargo build -p keepassity-ffi --release`; - publishes the self-contained app with `scripts/publish-windows.ps1 -Version -Zip` into `out/dist/keepassity--win-x64/` and @@ -99,8 +105,9 @@ Build-provenance attestations for `out/dist/*` are generated by the workflow - G0 (real-database round trip), G3 (main flows) and G4 (sync, conflict, restore, install/uninstall) are signed off; their checklists record the signer and the evidence in the private process repository. -- The 30-day real-use acceptance is the remaining gate before tagging. It starts with the - 1.0.0 acceptance build and must pass with zero data loss before the `v1.0.0` tag is created. +- The 30-day real-use acceptance (G5) did not run before `v1.0.0` was published: the owner + chose to release the first version directly on 2026-12-01. It remains the gate for later + releases. ## Rollback diff --git a/docs/testing.md b/docs/testing.md index 01dd019..880aa11 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -30,11 +30,48 @@ manifest, Windows build, headless service tests; `-Full` adds the application se - `tests/app-core/Keepassity.Core.Tests`: settings round-trip/schema and credential storage, sync-state round-trip and per-user keying, deterministic WebDAV working-copy paths, the WebDAV client against an in-process mock server (PROPFIND, GET, conditional - PUT, 412, non-ASCII/percent-encoded paths), DPAPI credential round-trip (Windows), - backups (retention/restore, corrupted-backup rejection), diagnostics archive and logging. + PUT, 412, non-ASCII/percent-encoded paths), the sync coordinator's ordering and conflict + rules with fake remote/vault/core ports (including a local save landing during a download, + merge or upload snapshot, which must pause instead of being overwritten, and conflict copies + reused by hash-derived names even after a restart), the WebDAV open ordering (pending bytes are only + promoted after the master password opens them; one end-to-end case runs with the real core + and the loopback WebDAV server), the vault session's single-writer rules (lock ownership, + external-change refusal, save serialization, replacement/restore with backups, write-idle + tracking used by the shutdown drain, a failed save leaving the session usable for a retry, reads + serialized with writes), the database lock's two layers (shared-folder lock taken/removed, a + lock held by another account refuses the open, an unwritable folder falls back to the account + lock), the TOTP display state machine (window countdown, pre-fetch, entry + switch, a failing source shown as unavailable rather than throwing), new-database + preparation (create-only local write, WebDAV working copy with a clean baseline), DPAPI + credential round-trip (Windows), backups (retention/restore, corrupted-backup rejection, + the same-volume rename fallback for volumes without `File.Replace`, + the run marker that reports an unclean previous session (clean close, dead process, live + process, malformed marker, atomic write), + the WebDAV cache cleanup (clean+old copies pruned with their backups/metadata/state and + forgotten in the recent list, while dirty, recent, unknown-provenance, hash-mismatched and + listed copies stay), + the diagnostics export (unique names within one millisecond, readable archive without database + paths/URLs/usernames, newest ten retained, crash-left temporaries removed), + WebDAV per-request timeouts (short metadata bound, long transfer bound, stalled transfers fail + with a clear message, caller cancellation preserved), + upload size verification (a loopback server that stores fewer bytes but answers 2xx is reported + as an incomplete upload), + unreadable-remote handling (the default pause keeps the local vault untouched and dirty and + preserves the unreadable bytes next to it, the explicit repair uploads the verified local copy + and records a clean baseline), + crash-residue cleanup (save/restore/backup temporaries at unlock and across the application + data tree, fresh files and unrelated files kept), + the last-moment replace guard (save, sync replacement and backup restore abort on an external + change and keep the live file plus the recovery backup), + log bounds (two writers on one day file, read-while-writing, size-cap rotation, retention and + the total-size ceiling), + recovery candidate selection: newest decryptable backup wins while corrupt, unreadable and + wrong-password candidates are skipped, verified against the real core as well), + diagnostics archive and logging. - `apps/windows` `--selftest`: non-UI application smoke test (open fixture copy -> list -> - TOTP -> save -> reopen). It exits non-zero on failure and writes counts/status only, never - secrets. + TOTP -> save -> backup create/restore -> reopen -> verify, plus localization, launch-argument, + single-instance payload and merge-fidelity checks). It exits non-zero on failure and writes + counts/status only, never secrets. ## Fixtures @@ -56,15 +93,35 @@ manifest, Windows build, headless service tests; `-Full` adds the application se ## UI strings -The Windows shell is English-only. `tools/check-ui-strings.ps1` scans `apps/windows/**/*.cs` -and `*.xaml` (excluding `bin/`, `obj/` and test/fixture directories) for hard-coded CJK text -and fails with `file:line`. The only allowed hits are the two documented data-matching -literals in `MainWindow.xaml.cs` (`回收站` and `模板`, the localized KeePass group names for -the recycle bin and templates groups — compared against database content, never shown in the -UI). Run it locally with: +The Windows shell ships English and Simplified Chinese and can switch at runtime (see +`apps/windows/Keepassity.App/Localization/`). All user-visible shell text lives in the +embedded catalogs under `apps/windows/Keepassity.Core/Localization/*.zh-CN.json`; the English +source text is the catalog key, so an untranslated string falls back to English instead of a +raw key. Code uses `Loc.T(...)` / `Loc.TLong(...)`; XAML uses the `loc:LocMarkup.Text`, +`ToolTip`, `Name` and `HelpText` attached properties. + +Two gates protect this: + +- `tools/check-ui-strings.ps1` scans `apps/windows/**/*.cs` and `*.xaml` (excluding `bin/`, + `obj/` and test/fixture directories) for hard-coded CJK text and fails with `file:line`, so + translations cannot leak into the sources. The only allowed hits are the two documented + data-matching literals in `MainWindow.xaml.cs` (`回收站` and `模板`, the localized KeePass + group names for the recycle bin and templates groups — compared against database content, + never shown in the UI). +- `tools/check-localization.ps1` cross-checks the sources against the catalogs: every + `Loc.T`/`Loc.TLong` call and XAML attached-property key must have a translation, composite + format placeholders (`{0}`…) must match between key and translation, catalog files must + parse and must not define the same key twice; unused entries, identical (untranslated) + values and suspicious unwrapped UI literals are reported as warnings. It also fails when a + catalog key or translation contains the lowercase product name: UI text spells the product + **Keepassity**, while `keepassity` is reserved for file/folder names, environment variables, + identifiers and URLs. + +Run both locally with: ```powershell powershell -NoProfile -ExecutionPolicy Bypass -File tools\check-ui-strings.ps1 +powershell -NoProfile -ExecutionPolicy Bypass -File tools\check-localization.ps1 ``` ## Adding a test @@ -85,7 +142,8 @@ powershell -NoProfile -ExecutionPolicy Bypass -File tools\check-ui-strings.ps1 - `ffi` — C harness (`kp_smoke.c`) and C# P/Invoke smoke, building the FFI library on Ubuntu; - `app` — Windows build of the WinUI shell, headless `tests/app-core` tests, two `--selftest` cases, and an informational dependency-vulnerability audit; -- `ui-strings` — `tools/check-ui-strings.ps1` (English-UI check); +- `ui-strings` — `tools/check-ui-strings.ps1` (no hard-coded CJK in shell sources) and + `tools/check-localization.ps1` (catalog completeness/freshness); - `secret-scan` — gitleaks; - `supply-chain` — `cargo deny check`; - `public-hygiene` — public allowlist check (`scripts/check-public.ps1`). @@ -94,6 +152,14 @@ The release workflow (`.github/workflows/release.yml`) additionally runs `cargo --workspace`, the `tests/app-core` suite and `scripts/verify-fixtures.ps1` before packaging, then self-tests the published application and builds the installer. +On a machine with Inno Setup, `scripts/verify-installer-runtime.ps1 -Version -SourceDir +` builds a throwaway installer with its own AppId and mutex (`TestMode`: no +shortcuts, no file-association registry writes, no Run entry), installs it, upgrades it, runs the +installed app's `--selftest` against a temporary data directory and uninstalls it. It asserts that +a file a user put next to the executable and the application data directory survive the +uninstall, while the real installation under `%LOCALAPPDATA%\Programs\keepassity` and the real +HKCU associations are unchanged. + ## Fuzzing `.github/workflows/fuzz.yml` is a separate scheduled workflow (03:00 UTC plus manual @@ -109,7 +175,7 @@ locally with `cargo +nightly fuzz run ` from `crates/core/fuzz/` (see it | Rust | `cargo fmt --check`, `cargo clippy --workspace --all-targets -D warnings`, `cargo test --workspace` | clippy is the Rust static analyzer; CodeQL has no Rust support | | Rust dependencies | `cargo deny check` (licenses, advisories, bans) in the `supply-chain` job | config in `deny.toml`, now including a sources policy | | C# / WinUI | `dotnet build` of the solution + the project-level publish path, CodeQL `csharp` (`security-extended`, generated files excluded) | CodeQL only analyzes the C# side; there is no C# formatting gate yet (tracked as a v1.x idea) | -| App text | `tools/check-ui-strings.ps1` (no hard-coded non-English UI strings) | keeps the UI English-only | +| App text | `tools/check-ui-strings.ps1` (no hard-coded CJK in shell sources) + `tools/check-localization.ps1` (catalog completeness) | UI text lives in the embedded language catalogs, never in the sources | | KDBX/parsers | fuzzing (`crates/core/fuzz`, nightly job) | panics inside the guarded upstream reader are classified, see `crates/core/fuzz/README.md` | CodeQL does not support Rust (checked 2026-11); the Rust side relies on clippy, the diff --git a/global.json b/global.json index 1e05653..d46d21e 100644 --- a/global.json +++ b/global.json @@ -1,7 +1,7 @@ { "sdk": { - "version": "8.0.100", - "rollForward": "latestMajor", + "version": "10.0.100", + "rollForward": "latestFeature", "allowPrerelease": false } } diff --git a/installer/keepassity.iss b/installer/keepassity.iss index 259e542..4d30e4d 100644 --- a/installer/keepassity.iss +++ b/installer/keepassity.iss @@ -1,4 +1,4 @@ -#define AppName "keepassity" +#define AppName "Keepassity" #ifndef AppVersion #define AppVersion "1.0.0" #endif @@ -8,10 +8,22 @@ #ifndef OutputDir #define OutputDir "..\..\out\dist" #endif -#define AppExe "Keepassity.exe" +#ifndef AppExe + #define AppExe "Keepassity.exe" +#endif +; Overridable so scripts/verify-installer-runtime.ps1 can build a throwaway +; installer with its own AppId/mutex and without shell integration, exercising +; install -> upgrade -> run -> uninstall against a temporary folder while the +; real installed copy stays untouched. +#ifndef AppId + #define AppId "{{A7E3B1F2-9D44-4C7A-A1B2-6F5E8D9C0123}" +#endif +#ifndef AppMutexName + #define AppMutexName "Local\keepassity-windows-app" +#endif [Setup] -AppId={{A7E3B1F2-9D44-4C7A-A1B2-6F5E8D9C0123} +AppId={#AppId} AppName={#AppName} AppVersion={#AppVersion} AppVerName={#AppName} {#AppVersion} @@ -39,22 +51,23 @@ UninstallDisplayIcon={app}\{#AppExe} ; install/uninstall (Inno Setup help: [Setup] ChangesAssociations). ChangesAssociations=yes ; Setup/uninstaller icon (the same multi-size icon the app uses). -SetupIconFile=..\apps\windows\Keepassity.Mock\Assets\app.ico +SetupIconFile=..\apps\windows\Keepassity.App\Assets\app.ico ; Refuse to install/uninstall while keepassity is running. The name must match ; the mutex the app creates at startup (App.xaml.cs, App.OnLaunched: ; new Mutex(true, @"Local\keepassity-windows-app")). -AppMutex=Local\keepassity-windows-app +AppMutex={#AppMutexName} ; GPL-3.0-or-later license page in the wizard. LicenseFile=..\LICENSE VersionInfoVersion={#AppVersion} -VersionInfoProductName=keepassity -VersionInfoDescription=keepassity Setup +VersionInfoProductName=Keepassity +VersionInfoDescription=Keepassity Setup VersionInfoCompany=simplenty VersionInfoCopyright=Copyright (C) 2026 the keepassity contributors [Files] Source: "{#SourceDir}\*"; DestDir: "{app}"; Flags: recursesubdirs createallsubdirs ignoreversion +#ifndef TestMode [Icons] Name: "{autoprograms}\keepassity"; Filename: "{app}\{#AppExe}" Name: "{autodesktop}\keepassity"; Filename: "{app}\{#AppExe}" @@ -70,23 +83,27 @@ Name: "{autodesktop}\keepassity"; Filename: "{app}\{#AppExe}" ; * Applications\\SupportedTypes advertises the file type to the shell. ; The .kdbx default value is deliberately NOT written: silently taking over the ; default handler is an anti-pattern (and ignored by Windows 10+ anyway). -Root: HKCU; Subkey: "Software\Classes\keepassity.kdbx"; ValueType: string; ValueName: ""; ValueData: "keepassity database"; Flags: uninsdeletekey +Root: HKCU; Subkey: "Software\Classes\keepassity.kdbx"; ValueType: string; ValueName: ""; ValueData: "Keepassity database"; Flags: uninsdeletekey Root: HKCU; Subkey: "Software\Classes\keepassity.kdbx\DefaultIcon"; ValueType: string; ValueName: ""; ValueData: "{app}\{#AppExe},0"; Flags: uninsdeletekey Root: HKCU; Subkey: "Software\Classes\keepassity.kdbx\shell\open\command"; ValueType: string; ValueName: ""; ValueData: """{app}\{#AppExe}"" ""%1"""; Flags: uninsdeletekey ; A value under a shared key belongs to us, not the key: delete only the value. Root: HKCU; Subkey: "Software\Classes\.kdbx\OpenWithProgids"; ValueType: string; ValueName: "keepassity.kdbx"; ValueData: ""; Flags: uninsdeletevalue Root: HKCU; Subkey: "Software\Classes\Applications\{#AppExe}\SupportedTypes"; ValueType: string; ValueName: ".kdbx"; ValueData: ""; Flags: uninsdeletekey -Root: HKCU; Subkey: "Software\Classes\Applications\{#AppExe}"; ValueType: string; ValueName: "FriendlyAppName"; ValueData: "keepassity"; Flags: uninsdeletekey +Root: HKCU; Subkey: "Software\Classes\Applications\{#AppExe}"; ValueType: string; ValueName: "FriendlyAppName"; ValueData: "Keepassity"; Flags: uninsdeletekey [Run] -Filename: "{app}\{#AppExe}"; Description: "Launch keepassity"; Flags: nowait postinstall skipifsilent +Filename: "{app}\{#AppExe}"; Description: "Launch Keepassity"; Flags: nowait postinstall skipifsilent +#endif [InstallDelete] ; Remove the pre-1.0 binary name so an upgrade does not leave a stale executable -; (v0.1.0 shipped Keepassity.Mock.exe; v1.0.0 ships Keepassity.exe). +; (v0.1.0 shipped Keepassity.Mock.exe; v1.0.0 ships Keepassity.exe). Only exact +; files we used to install are listed: a wildcard could delete a user file that +; happens to sit in the installation folder. Type: files; Name: "{app}\Keepassity.Mock.exe" Type: files; Name: "{app}\Keepassity.Mock.pdb" -Type: files; Name: "{app}\Keepassity.Mock.*" -[UninstallDelete] -Type: filesandordirs; Name: "{app}" +; Deliberately no [UninstallDelete] section. Inno Setup removes the files it +; installed and only removes directories it can leave empty; `filesandordirs +; {app}` would delete a vault, a backup or any other file a user put next to the +; executable. An uninstall must never remove data it did not create. diff --git a/public.allowlist b/public.allowlist index a4641d6..64594a9 100644 --- a/public.allowlist +++ b/public.allowlist @@ -36,8 +36,12 @@ scripts/publish-windows.ps1 scripts/selftest.ps1 scripts/verify-fixtures.ps1 scripts/make-checksums.ps1 +scripts/verify-checksums.ps1 scripts/test.ps1 +scripts/check-structure.ps1 +scripts/structure-budget.json scripts/build-installer.ps1 +scripts/verify-installer-runtime.ps1 installer/** .github/workflows/release.yml .github/dependabot.yml @@ -52,4 +56,4 @@ installer/** .github/codeql/codeql-config.yml crates/core/tests/data/extreme-kdf-rounds.bin apps/windows/Keepassity.Core/WebDavTls.cs -tests/app-core/Keepassity.Core.Tests/WebDavTlsTests.cs \ No newline at end of file +tests/app-core/Keepassity.Core.Tests/WebDavTlsTests.cs diff --git a/scripts/check-structure.ps1 b/scripts/check-structure.ps1 new file mode 100644 index 0000000..1292877 --- /dev/null +++ b/scripts/check-structure.ps1 @@ -0,0 +1,224 @@ +<# +.SYNOPSIS + Structure budget guard (ADR-0035): line budgets, concentration cap, async void + shape and the MVVM layering boundary. Exit 0 pass, 1 fail, 2 cannot run. +.EXAMPLE + powershell -NoProfile -ExecutionPolicy Bypass -File scripts/check-structure.ps1 + powershell -NoProfile -ExecutionPolicy Bypass -File scripts/check-structure.ps1 -SelfTest +#> +param([switch]$SelfTest) +$ErrorActionPreference = 'Stop' + +$script:failures = 0 +function Report([string]$name, [bool]$ok, [string]$detail) { + if ($ok) { Write-Host ("PASS " + $name) } + else { Write-Host ("FAIL " + $name + " " + $detail); $script:failures++ } +} + +# Runs a detector that is EXPECTED to fail; verifies it did, then restores the +# failure counter so only unexpected failures count at the end. +function Test-ExpectedRed([string]$name, [scriptblock]$detector) { + $before = $script:failures + & $detector + $wentRed = ($script:failures -gt $before) + $script:failures = $before + Report $name $wentRed 'detector must report FAIL on the synthetic violation' +} + +function Count-Lines([string]$path) { + return ([System.IO.File]::ReadAllLines($path)).Count +} + +function Test-IsExcluded([System.IO.FileInfo]$file, [string[]]$dirNames, [string[]]$patterns) { + $norm = $file.FullName -replace '/', '\' + foreach ($d in $dirNames) { + if ($norm -like ('*\' + $d + '\*')) { return $true } + } + foreach ($p in $patterns) { if ($file.Name -like $p) { return $true } } + return $false +} + +function Get-CountedFiles([string]$root, [string[]]$tops, [string[]]$extensions, [string[]]$dirNames, [string[]]$patterns) { + $all = @() + foreach ($t in $tops) { + $dir = Join-Path $root $t + if (-not (Test-Path -LiteralPath $dir)) { continue } + $all += Get-ChildItem -LiteralPath $dir -Recurse -File -ErrorAction SilentlyContinue + } + $result = @() + foreach ($f in $all) { + $ext = $f.Extension.ToLowerInvariant() + if ($extensions -notcontains $ext) { continue } + if (Test-IsExcluded $f $dirNames $patterns) { continue } + $result += $f + } + return $result +} + +function Test-LineBudget([string]$name, [int]$lines, [int]$max) { + Report $name ($lines -le $max) ("lines=" + $lines + " cap=" + $max) +} + +function Test-Concentration([int]$maxLines, [int]$totalLines, [double]$capPercent, [string]$largestName) { + $pct = 0 + if ($totalLines -gt 0) { $pct = [math]::Round(100.0 * $maxLines / $totalLines, 2) } + Report ('concentration ' + $pct + '% <= ' + $capPercent + '%') ($pct -le $capPercent) ('largest=' + $largestName + ' ' + $maxLines + ' / total=' + $totalLines) +} + +function Test-AsyncVoid([string[]]$files, [int]$max, [string]$handlerPattern, [string[]]$allowlist) { + $total = 0 + $bad = @() + foreach ($f in $files) { + if (-not $f.ToLowerInvariant().EndsWith('.cs')) { continue } + $lines = [System.IO.File]::ReadAllLines($f) + for ($i = 0; $i -lt $lines.Count; $i++) { + if ($lines[$i] -match 'async\s+void\s+(\w+)\s*\(') { + $total++ + $mname = $Matches[1] + $isHandler = ($mname -match $handlerPattern) + $isAllowed = ($allowlist -contains $mname) + if (-not ($isHandler -or $isAllowed)) { + $bad += ($f + ':' + ($i + 1) + ' ' + $mname) + } + } + } + } + $detail = 'count=' + $total + ' cap=' + $max + if ($bad.Count -gt 0) { $detail = $detail + '; non-handler: ' + ($bad -join ', ') } + Report 'async void within budget and handler-shaped' ($total -le $max -and $bad.Count -eq 0) $detail +} + +function Test-ViewModelBoundary([string]$vmDir, [string[]]$forbiddenUsings, [string[]]$forbiddenTokens) { + $csproj = Get-ChildItem -LiteralPath $vmDir -Filter '*.csproj' -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($null -eq $csproj) { Report 'viewmodels boundary' $false ('no csproj under ' + $vmDir); return } + $ok = $true + $detail = '' + $text = [System.IO.File]::ReadAllText($csproj.FullName) + foreach ($t in $forbiddenTokens) { + if ($text.Contains($t)) { $ok = $false; $detail = $detail + 'csproj token ' + $t + '; ' } + } + $sources = Get-ChildItem -LiteralPath $vmDir -Recurse -File -Filter '*.cs' + foreach ($f in $sources) { + $lines = [System.IO.File]::ReadAllLines($f.FullName) + foreach ($line in $lines) { + foreach ($u in $forbiddenUsings) { + if ($line.TrimStart().StartsWith($u)) { + $ok = $false + $detail = $detail + $f.Name + ' uses "' + $u + '"; ' + } + } + } + } + if ($detail.Length -gt 200) { $detail = $detail.Substring(0, 200) } + Report 'viewmodels boundary (no WinUI/WinRT/Windows SDK)' $ok $detail +} + +# ---- main mode ---- +if (-not $SelfTest) { + $budgetPath = Join-Path $PSScriptRoot 'structure-budget.json' + if (-not (Test-Path -LiteralPath $budgetPath)) { + Write-Host 'TOOL_MISSING: structure-budget.json next to check-structure.ps1' + exit 2 + } + $b = Get-Content -LiteralPath $budgetPath -Raw | ConvertFrom-Json + $repoRoot = Split-Path -Parent $PSScriptRoot + + $counted = Get-CountedFiles $repoRoot $b.countedRoots @('.cs', '.rs') $b.excludedDirNames $b.excludedFilePatterns + $linesByFile = @{} + $total = 0 + foreach ($f in $counted) { + $n = Count-Lines $f.FullName + $linesByFile[$f.FullName] = $n + $total += $n + } + + # 1. main file budget + $mainPath = Join-Path $repoRoot ($b.mainFile.path -replace '/', '\') + if (Test-Path -LiteralPath $mainPath) { + Test-LineBudget ('main file ' + $b.mainFile.path) (Count-Lines $mainPath) $b.mainFile.maxLines + } else { + Report ('main file ' + $b.mainFile.path) $false 'missing' + } + + # 2. production C# single-file budget (main file excluded, it has its own) + $appsDir = Join-Path $repoRoot 'apps\windows' + $worst = 0; $worstName = '' + $allow = @() + if ($b.production.allowlist) { $allow = @($b.production.allowlist | ForEach-Object { (Join-Path $repoRoot ($_ -replace '/', '\')) }) } + foreach ($f in $counted) { + if ($f.Extension -ne '.cs') { continue } + if (-not $f.FullName.StartsWith($appsDir, [System.StringComparison]::OrdinalIgnoreCase)) { continue } + if ($b.production.excludeMainFile -and $f.FullName -eq $mainPath) { continue } + if ($allow -contains $f.FullName) { continue } + $n = $linesByFile[$f.FullName] + if ($n -ge $b.production.minLines -and $n -gt $worst) { $worst = $n; $worstName = $f.Name } + } + Report ('production C# single file (>= ' + $b.production.minLines + ' lines) within ' + $b.production.csharpMaxLines) ($worst -le $b.production.csharpMaxLines) ('worst=' + $worstName + ' ' + $worst) + + # 3. production Rust single-file budget (src trees only) + $worst = 0; $worstName = '' + foreach ($r in $b.production.rustSourceRoots) { + $dir = Join-Path $repoRoot ($r -replace '/', '\') + if (-not (Test-Path -LiteralPath $dir)) { continue } + Get-ChildItem -LiteralPath $dir -Recurse -File -Filter '*.rs' -ErrorAction SilentlyContinue | ForEach-Object { + $n = Count-Lines $_.FullName + if ($n -ge $b.production.minLines -and $n -gt $worst) { $worst = $n; $worstName = $_.Name } + } + } + Report ('production Rust single file (>= ' + $b.production.minLines + ' lines) within ' + $b.production.rustMaxLines) ($worst -le $b.production.rustMaxLines) ('worst=' + $worstName + ' ' + $worst) + + # 4. concentration: largest single file over the whole handwritten tree + $max = 0; $maxName = '' + foreach ($k in $linesByFile.Keys) { + if ($linesByFile[$k] -gt $max) { $max = $linesByFile[$k]; $maxName = (Split-Path -Leaf $k) } + } + Test-Concentration $max $total $b.maxConcentrationPercent $maxName + + # 5. async void + $csAll = @($counted | Where-Object { $_.Extension -eq '.cs' } | ForEach-Object { $_.FullName }) + Test-AsyncVoid $csAll $b.asyncVoid.max $b.asyncVoid.handlerPattern $b.asyncVoid.allowlist + + # 6. viewmodels boundary + $vmDir = Join-Path $repoRoot ($b.viewModels.projectDir -replace '/', '\') + Test-ViewModelBoundary $vmDir $b.viewModels.forbiddenUsings $b.viewModels.forbiddenPackageTokens + + if ($script:failures -gt 0) { Write-Host ('STRUCTURE BUDGET FAIL (' + $script:failures + ')'); exit 1 } + Write-Host 'STRUCTURE BUDGET PASS' + exit 0 +} + +# ---- self-test mode: every detector must go red on a synthetic violation ---- +$tmp = Join-Path ([System.IO.Path]::GetTempPath()) ('structure-selftest-' + [guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $tmp | Out-Null +try { + $tenLines = New-Object 'System.Collections.Generic.List[string]' + 1..10 | ForEach-Object { $tenLines.Add('// line') } + $big = Join-Path $tmp 'big.cs' + [System.IO.File]::WriteAllLines($big, $tenLines) + + Test-ExpectedRed 'selftest: line budget detects overrun (10 vs 5)' { Test-LineBudget 'selftest: inner (expect FAIL)' 10 5 } + Test-LineBudget 'selftest: line budget accepts 10 vs 50' 10 50 + + $badHandler = Join-Path $tmp 'bad.cs' + [System.IO.File]::WriteAllLines($badHandler, [string[]]@('private async void Bad() { }')) + Test-ExpectedRed 'selftest: non-handler async void detected' { Test-AsyncVoid @($badHandler) 5 '^[A-Za-z][A-Za-z0-9]*_\w+$' @() } + + $goodHandler = Join-Path $tmp 'good.cs' + [System.IO.File]::WriteAllLines($goodHandler, [string[]]@('private async void Ok_Click() { }')) + Test-AsyncVoid @($goodHandler) 5 '^[A-Za-z][A-Za-z0-9]*_\w+$' @() + + $vm = Join-Path $tmp 'vm' + New-Item -ItemType Directory -Path $vm | Out-Null + [System.IO.File]::WriteAllLines((Join-Path $vm 'bad.cs'), [string[]]@('using Microsoft.UI.Xaml;')) + [System.IO.File]::WriteAllText((Join-Path $vm 'V.csproj'), '') + Test-ExpectedRed 'selftest: viewmodels boundary detects WinUI using' { Test-ViewModelBoundary $vm @('using Microsoft.UI', 'using Windows.', 'using WinRT') @('WindowsAppSDK') } + + Test-ExpectedRed 'selftest: concentration 20% vs cap 16%' { Test-Concentration 20 100 16 'synthetic.cs' } + Test-Concentration 5 100 16 'synthetic.cs' +} finally { + Remove-Item -LiteralPath $tmp -Recurse -Force -ErrorAction SilentlyContinue +} + +if ($script:failures -gt 0) { Write-Host ('SELF-TEST FAIL (' + $script:failures + ')'); exit 1 } +Write-Host 'SELF-TEST PASS' +exit 0 diff --git a/scripts/make-checksums.ps1 b/scripts/make-checksums.ps1 index 65559f9..bff4ffd 100644 --- a/scripts/make-checksums.ps1 +++ b/scripts/make-checksums.ps1 @@ -1,7 +1,12 @@ # SPDX-License-Identifier: GPL-3.0-or-later <# .SYNOPSIS - Write a SHA256SUMS file for the release artifacts in a directory. + Write a portable, deterministic SHA256SUMS file for release artifacts. + +.DESCRIPTION + Every regular artifact except SHA256SUMS itself is hashed, including the SBOM. + Lines use LF endings and lowercase hex so the file works with GNU coreutils + (sha256sum -c) as well as Windows tooling. #> param( [string]$Directory @@ -17,14 +22,18 @@ if (-not (Test-Path $Directory)) { } $files = Get-ChildItem $Directory -File | - Where-Object { $_.Name -notlike 'SHA256SUMS*' -and $_.Name -notlike '*.spdx.json' } | + Where-Object { $_.Name -ne 'SHA256SUMS' } | Sort-Object Name +if (@($files).Count -eq 0) { + throw "no release artifacts found in $Directory" +} + $lines = foreach ($file in $files) { $hash = (Get-FileHash $file.FullName -Algorithm SHA256).Hash.ToLowerInvariant() "$hash $($file.Name)" } $path = Join-Path $Directory 'SHA256SUMS' -$lines = @($lines) -[System.IO.File]::WriteAllLines($path, $lines, (New-Object System.Text.UTF8Encoding($false))) +[System.IO.File]::WriteAllText($path, (($lines -join "`n") + "`n"), + (New-Object System.Text.UTF8Encoding($false))) Write-Host "checksums: $path" $lines | ForEach-Object { Write-Host " $_" } diff --git a/scripts/publish-windows.ps1 b/scripts/publish-windows.ps1 index 63922a0..446cdf7 100644 --- a/scripts/publish-windows.ps1 +++ b/scripts/publish-windows.ps1 @@ -12,14 +12,18 @@ param( $ErrorActionPreference = "Stop" $root = Split-Path -Parent $PSScriptRoot -$project = Join-Path $root "apps/windows/Keepassity.Mock/Keepassity.Mock.csproj" +$project = Join-Path $root "apps/windows/Keepassity.App/Keepassity.App.csproj" if ([string]::IsNullOrWhiteSpace($OutputRoot)) { $OutputRoot = Join-Path $root "dist" } if ([string]::IsNullOrWhiteSpace($Version)) { + # Read the single version source with the XML DOM instead of the PowerShell + # adapter: Windows PowerShell 5.1 returns an XmlElement for + # $props.Project.PropertyGroup.KeepassityVersion, which turned the version + # property into "System.Xml.XmlElement" and made restore fail. [xml]$props = Get-Content (Join-Path $root "Directory.Build.props") - $Version = ($props.Project.PropertyGroup | Where-Object { $_.KeepassityVersion } | - Select-Object -First 1).KeepassityVersion + $versionNode = $props.SelectSingleNode('/Project/PropertyGroup/KeepassityVersion') + $Version = if ($versionNode) { $versionNode.InnerText.Trim() } else { "" } if ([string]::IsNullOrWhiteSpace($Version)) { $Version = "1.0.0-dev" } diff --git a/scripts/selftest.ps1 b/scripts/selftest.ps1 index 8178dbf..c182db6 100644 --- a/scripts/selftest.ps1 +++ b/scripts/selftest.ps1 @@ -42,14 +42,14 @@ if (-not $Exe) { # Pick the newest Release build: builds made with -p:Platform=x64 and a plain # `dotnet build` land in different bin subdirectories, and testing a stale # binary silently hides regressions. - $candidate = Get-ChildItem -Path (Join-Path $root 'apps/windows/Keepassity.Mock/bin') -Recurse -Filter 'Keepassity.exe' -ErrorAction SilentlyContinue | + $candidate = Get-ChildItem -Path (Join-Path $root 'apps/windows/Keepassity.App/bin') -Recurse -Filter 'Keepassity.exe' -ErrorAction SilentlyContinue | Where-Object { $_.FullName -match '\\Release\\' } | Sort-Object LastWriteTime -Descending | Select-Object -First 1 if ($candidate) { $Exe = $candidate.FullName } else { - $Exe = Join-Path $root 'apps/windows/Keepassity.Mock/bin/x64/Release/net8.0-windows10.0.19041.0/win-x64/Keepassity.exe' + $Exe = Join-Path $root 'apps/windows/Keepassity.App/bin/x64/Release/net10.0-windows10.0.19041.0/win-x64/Keepassity.exe' } } if (-not (Test-Path $Exe)) { diff --git a/scripts/structure-budget.json b/scripts/structure-budget.json new file mode 100644 index 0000000..5761c78 --- /dev/null +++ b/scripts/structure-budget.json @@ -0,0 +1,39 @@ +{ + "stage": "P8", + "adr": "0036", + "note": "Line budgets are frozen at the 2026-11-17 baseline and may only move down (ratchet). Production code is capped at 400 lines per C# file and 550 per Rust file; three single-function C# files are explicitly allowlisted because splitting them would mean editing behaviour rather than moving code. Test files are not capped by this guard: they are linear check lists, so the concentration cap is what keeps any single one of them from dominating the tree.", + "mainFile": { + "path": "apps/windows/Keepassity.App/MainWindow.xaml.cs", + "maxLines": 87 + }, + "production": { + "roots": ["apps/windows", "crates"], + "minLines": 300, + "excludeMainFile": true, + "csharpMaxLines": 400, + "allowlist": [ + "apps/windows/Keepassity.App/MainWindow.LegacyProfile.cs", + "apps/windows/Keepassity.App/MainWindow.NewDatabase.cs", + "apps/windows/Keepassity.App/AppSelfTest.cs" + ], + "allowlistNote": "LegacyProfile is one ADR-0034 migration function that M7-08 deletes; NewDatabase and AppSelfTest each wrap one long linear routine (a create-database flow and a self-test script) whose split would change behaviour, not layout.", + "rustMaxLines": 550, + "rustSourceRoots": ["crates/core/src", "crates/ffi/src", "crates/cli/src"], + "maxFfiStdFsLines": 3 + }, + "maxConcentrationPercent": 2, + "countedRoots": ["apps", "tests", "tools", "crates"], + "excludedDirNames": ["bin", "obj", "target", "vendor", "node_modules", "out", ".git"], + "excludedFilePatterns": ["*.g.cs", "*.g.i.cs", "*.Designer.cs"], + "asyncVoid": { + "max": 24, + "handlerPattern": "^[A-Za-z][A-Za-z0-9]*_\\w+$", + "allowlist": ["RefreshEntries"], + "allowlistNote": "RefreshEntries is a plain private method, not an event handler; recorded 2026-11-16 and to be converged in M7-13, not extended." + }, + "viewModels": { + "projectDir": "apps/windows/Keepassity.ViewModels", + "forbiddenUsings": ["using Microsoft.UI", "using Windows.", "using WinRT", "using Microsoft.Windows"], + "forbiddenPackageTokens": ["WindowsAppSDK", "Microsoft.WinUI", "WinRT", "H.NotifyIcon"] + } +} diff --git a/scripts/test.ps1 b/scripts/test.ps1 index 57d76b7..87f5e4a 100644 --- a/scripts/test.ps1 +++ b/scripts/test.ps1 @@ -14,13 +14,36 @@ param( $ErrorActionPreference = 'Continue' $root = Split-Path -Parent $PSScriptRoot Push-Location $root -# Prefer a user-local SDK when one is installed: the machine-wide SDK can be -# broken (missing workload resolvers) while a dotnet-install copy works. CI has -# no user-local copy, so this is a no-op there. +# Prefer a user-local SDK when it is new enough for global.json: the +# machine-wide SDK can be broken (missing workload resolvers) while a +# dotnet-install copy works. An older user-local SDK must not shadow the +# machine-wide one after a framework upgrade, so compare versions first. $localDotnet = Join-Path $env:USERPROFILE '.dotnet' if (Test-Path (Join-Path $localDotnet 'dotnet.exe')) { - $env:PATH = $localDotnet + ';' + $env:PATH - $env:DOTNET_ROOT = $localDotnet + $required = $null + try { + $required = [version](Get-Content (Join-Path $root 'global.json') -Raw | + ConvertFrom-Json).sdk.version + } catch { + $required = $null + } + $localCompatible = $null + $sdkDirectory = Join-Path $localDotnet 'sdk' + if (Test-Path $sdkDirectory) { + $localCompatible = Get-ChildItem $sdkDirectory -Directory | + ForEach-Object { + try { [version]$_.Name } catch { $null } + } | + Where-Object { $_ -ne $null -and ($required -eq $null -or $_ -ge $required) } | + Sort-Object -Descending | + Select-Object -First 1 + } + if ($localCompatible) { + $env:PATH = $localDotnet + ';' + $env:PATH + $env:DOTNET_ROOT = $localDotnet + } else { + Write-Host ("user-local .NET SDK is older than global.json requires ({0}); using the machine-wide SDK" -f $required) + } } $failures = 0 function Run([string]$name, [scriptblock]$action) { @@ -36,6 +59,8 @@ Run 'cargo fmt' { cargo fmt --all -- --check } Run 'cargo clippy' { cargo clippy --workspace --all-targets -- -D warnings } Run 'cargo test' { cargo test --workspace } Run 'fixtures' { powershell -NoProfile -ExecutionPolicy Bypass -File scripts/verify-fixtures.ps1 } +Run 'ui strings' { powershell -NoProfile -ExecutionPolicy Bypass -File tools/check-ui-strings.ps1 } +Run 'localization' { powershell -NoProfile -ExecutionPolicy Bypass -File tools/check-localization.ps1 -Strict } Run 'app build' { dotnet build apps/windows/Keepassity.sln -c Debug } $coreTestsDir = Join-Path $root 'out/tmp/core-tests' New-Item -ItemType Directory -Force -Path $coreTestsDir | Out-Null diff --git a/scripts/verify-checksums.ps1 b/scripts/verify-checksums.ps1 new file mode 100644 index 0000000..734db20 --- /dev/null +++ b/scripts/verify-checksums.ps1 @@ -0,0 +1,48 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +<# +.SYNOPSIS + Verify every entry in a SHA256SUMS file against the files in its directory. + +.DESCRIPTION + Recomputes each digest and fails on a missing file, malformed line or mismatch. + This is the release step that proves the checksum file belongs to the exact + artifacts being uploaded. +#> +param( + [string]$Directory +) + +$ErrorActionPreference = 'Stop' +$root = Split-Path -Parent $PSScriptRoot +if ([string]::IsNullOrWhiteSpace($Directory)) { + $Directory = Join-Path $root 'dist' +} +$sums = Join-Path $Directory 'SHA256SUMS' +if (-not (Test-Path $sums)) { + throw "checksum file not found: $sums" +} + +$lines = @(Get-Content $sums) +$checked = 0 +foreach ($line in $lines) { + if ([string]::IsNullOrWhiteSpace($line)) { continue } + $match = [regex]::Match($line, '^([0-9a-fA-F]{64}) (.+)$') + if (-not $match.Success) { + throw "malformed checksum line: $line" + } + $expected = $match.Groups[1].Value.ToLowerInvariant() + $name = $match.Groups[2].Value + $path = Join-Path $Directory $name + if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { + throw "checksummed artifact is missing: $name" + } + $actual = (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() + if ($actual -ne $expected) { + throw "checksum mismatch for $name (expected $expected, got $actual)" + } + $checked++ +} +if ($checked -eq 0) { + throw "checksum file contains no artifacts: $sums" +} +Write-Host "checksums verified: $checked artifact(s)" diff --git a/scripts/verify-installer-runtime.ps1 b/scripts/verify-installer-runtime.ps1 new file mode 100644 index 0000000..118852d --- /dev/null +++ b/scripts/verify-installer-runtime.ps1 @@ -0,0 +1,225 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +<# +.SYNOPSIS + Exercise a throwaway installer end to end: install, upgrade, run, uninstall. + +.DESCRIPTION + Builds an Inno Setup package with its own AppId and mutex (TestMode: no + shortcuts, no file-association registry writes, no Run entry), installs it to a + temporary folder, installs it again to exercise the upgrade path, runs the + installed app's --selftest against a temporary data directory, then uninstalls + it. The checks prove two data-safety properties of the installer: + + * uninstall removes the files the installer created and nothing else; + * user data (a file a user put next to the executable, and the application + data directory) survives the uninstall. + + The real installed copy under %LOCALAPPDATA%\Programs\keepassity and the real + HKCU associations are captured before and after and must be unchanged. + + A workspace directory can carry the Low mandatory integrity label; Windows then + shows an invisible "Open File - Security Warning" before launching an + executable there. The script raises the freshly built setup and uninstaller to + Medium first, the same thing scripts/build-installer.ps1 does for the shipped + setup. + +.PARAMETER Version + Version compiled into the throwaway installer. + +.PARAMETER SourceDir + Published portable folder to package (scripts/publish-windows.ps1 output). + +.PARAMETER WorkDir + Optional scratch folder; defaults to out/tmp/installer-runtime. + +.PARAMETER KeepArtifacts + Keep the scratch folder instead of deleting it after a successful run. +#> +param( + [Parameter(Mandatory = $true)][string]$Version, + [Parameter(Mandatory = $true)][string]$SourceDir, + [string]$WorkDir, + [switch]$KeepArtifacts +) + +$ErrorActionPreference = 'Stop' +$root = Split-Path -Parent $PSScriptRoot +Set-Location $root + +if (-not (Test-Path $SourceDir)) { + throw "publish folder not found: $SourceDir" +} +$SourceDir = (Resolve-Path $SourceDir).Path +if (-not $WorkDir) { + $WorkDir = Join-Path $root 'out/tmp/installer-runtime' +} +$WorkDir = [IO.Path]::GetFullPath($WorkDir) +if (Test-Path $WorkDir) { + Remove-Item -Recurse -Force $WorkDir +} +$installerDir = Join-Path $WorkDir 'installer' +$appDir = Join-Path $WorkDir 'app' +$dataDir = Join-Path $WorkDir 'data' +$fixture = Join-Path $WorkDir 'fixture.kdbx' +New-Item -ItemType Directory -Force -Path $installerDir, $dataDir | Out-Null + +function Find-Iscc { + $candidates = @( + (Join-Path $env:ProgramFiles 'Inno Setup 6/ISCC.exe'), + (Join-Path ${env:ProgramFiles(x86)} 'Inno Setup 6/ISCC.exe'), + (Join-Path $env:LOCALAPPDATA 'Programs/Inno Setup 6/ISCC.exe') + ) | Where-Object { $_ -and (Test-Path $_) } + if ($candidates) { + return $candidates | Select-Object -First 1 + } + $found = Get-ChildItem 'C:\Program Files', 'C:\Program Files (x86)', ` + (Join-Path $env:LOCALAPPDATA 'Programs') -Recurse -Filter 'ISCC.exe' ` + -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($found) { + return $found.FullName + } + throw 'Inno Setup (ISCC.exe) was not found; install it to run this check.' +} + +function Set-MediumIntegrity([string]$Path) { + # Harmless on folders without the Low label; required when the workspace is + # Low integrity, otherwise ShellExecute hides behind a security-warning dialog. + try { + & icacls $Path /setintegritylevel Medium | Out-Null + } + catch { + Write-Warning "could not raise integrity of $Path (continuing): $_" + } +} + +function Invoke-Setup([string]$Path, [string]$Target) { + $process = Start-Process -FilePath $Path ` + -ArgumentList '/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/NOICONS', ` + "/DIR=$Target" -Wait -PassThru + if ($process.ExitCode -ne 0) { + throw "installer exited with $($process.ExitCode)" + } +} + +function Invoke-Uninstaller([string]$Path) { + $process = Start-Process -FilePath $Path ` + -ArgumentList '/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART' ` + -Wait -PassThru + if ($process.ExitCode -ne 0) { + throw "uninstaller exited with $($process.ExitCode)" + } +} + +$running = Get-Process Keepassity -ErrorAction SilentlyContinue +if ($running) { + throw 'Keepassity is running; close it before running the installer check.' +} + +$realInstall = Join-Path $env:LOCALAPPDATA 'Programs/keepassity/Keepassity.exe' +$realInstallBefore = Test-Path $realInstall +$realAssocBefore = Test-Path 'HKCU:\Software\Classes\keepassity.kdbx' +$oldSelftestPassword = $env:KEEPASSITY_SELFTEST_PASSWORD +$oldDataDir = $env:KEEPASSITY_DATA_DIR +$oldReport = $env:KEEPASSITY_SELFTEST_REPORT +$installed = $false +try { + $iscc = Find-Iscc + $appId = '{{' + [guid]::NewGuid().ToString().ToUpperInvariant() + '}' + $mutexName = 'Local\keepassity-installer-runtime-' + [guid]::NewGuid().ToString('N') + + & $iscc ` + "/DAppVersion=$Version" ` + "/DSourceDir=$SourceDir" ` + "/DOutputDir=$installerDir" ` + "/DAppId=$appId" ` + "/DAppMutexName=$mutexName" ` + '/DTestMode=1' ` + (Join-Path $root 'installer/keepassity.iss') + if ($LASTEXITCODE -ne 0) { + throw "ISCC failed with exit code $LASTEXITCODE" + } + $setup = Join-Path $installerDir "keepassity-$Version-win-x64-setup.exe" + if (-not (Test-Path $setup)) { + throw "installer was not produced: $setup" + } + Set-MediumIntegrity $setup + + Write-Host 'installer check: installing' + Invoke-Setup $setup $appDir + $installed = $true + $exe = Join-Path $appDir 'Keepassity.exe' + if (-not (Test-Path $exe)) { + throw 'install did not place Keepassity.exe' + } + + Write-Host 'installer check: upgrading' + Invoke-Setup $setup $appDir + if (-not (Test-Path $exe)) { + throw 'upgrade removed the executable' + } + + Write-Host 'installer check: running the installed app' + Copy-Item (Join-Path $root 'tests/fixtures/keepass-rs/test_db_few_rounds.kdbx') ` + $fixture -Force + Set-Content -Path (Join-Path $dataDir 'keepassity-data-marker.txt') -Value 'preserve' + $reportDirectory = Join-Path $dataDir 'selftest' + $report = Join-Path $reportDirectory ('keepassity-selftest-' + [guid]::NewGuid().ToString('N') + '.log') + $env:KEEPASSITY_SELFTEST_PASSWORD = 'demopass' + $env:KEEPASSITY_DATA_DIR = $dataDir + $env:KEEPASSITY_SELFTEST_REPORT = $report + # Start-Process -Wait (not &): the app is a GUI-subsystem executable, so a + # shell invocation returns before the self-test has written its report. + Set-MediumIntegrity $exe + $selftest = Start-Process -FilePath $exe ` + -ArgumentList '--selftest', $fixture, '--data-dir', $dataDir -Wait -PassThru + if ($selftest.ExitCode -ne 0) { + throw "the installed app's self-test failed with exit code $($selftest.ExitCode)" + } + if (-not (Test-Path $report)) { + $written = @(Get-ChildItem $reportDirectory -Filter '*.log' -ErrorAction SilentlyContinue) + throw "the installed app did not write its self-test report ($report); found $($written.Count) report(s)" + } + Set-Content -Path (Join-Path $appDir 'keepassity-user-note.txt') -Value 'preserve' + + Write-Host 'installer check: uninstalling' + $uninstaller = Join-Path $appDir 'unins000.exe' + if (-not (Test-Path $uninstaller)) { + throw 'installer did not place an uninstaller' + } + Set-MediumIntegrity $uninstaller + Invoke-Uninstaller $uninstaller + $installed = $false + Start-Sleep -Milliseconds 500 + + if (Test-Path $exe) { + throw 'uninstall left Keepassity.exe behind' + } + if (-not (Test-Path (Join-Path $appDir 'keepassity-user-note.txt'))) { + throw 'uninstall deleted a user file next to the executable' + } + if (-not (Test-Path (Join-Path $dataDir 'keepassity-data-marker.txt')) -or + -not (Test-Path $report)) { + throw 'uninstall deleted user data' + } + if ($realInstallBefore -ne (Test-Path $realInstall) -or + $realAssocBefore -ne (Test-Path 'HKCU:\Software\Classes\keepassity.kdbx')) { + throw 'the throwaway installer changed the real installation or associations' + } + + Write-Host 'PASS: install, upgrade, run and uninstall preserve user data' +} +finally { + if ($installed) { + $leftover = Join-Path $appDir 'unins000.exe' + if (Test-Path $leftover) { + Set-MediumIntegrity $leftover + try { Invoke-Uninstaller $leftover } catch { Write-Warning $_ } + } + } + $env:KEEPASSITY_SELFTEST_PASSWORD = $oldSelftestPassword + $env:KEEPASSITY_DATA_DIR = $oldDataDir + $env:KEEPASSITY_SELFTEST_REPORT = $oldReport + if (-not $KeepArtifacts) { + Remove-Item -Recurse -Force $WorkDir -ErrorAction SilentlyContinue + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/ArchitectureTests.cs b/tests/app-core/Keepassity.Core.Tests/ArchitectureTests.cs new file mode 100644 index 0000000..206f382 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/ArchitectureTests.cs @@ -0,0 +1,324 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Text; +using System.Text.RegularExpressions; + +namespace Keepassity.CoreTests; + +/// +/// Architecture assertions for ADR-0035 section 9: the dependency direction +/// between the C# layers and the purity of the Rust core. The real-tree checks +/// prove the tree is clean today; the self-proof section runs the same +/// detectors against synthetic violations and must see every one of them red. +/// +internal static class ArchitectureTests +{ + public static void Run(TestCheck check, string writableRoot) + { + string? root = FindRepoRoot(); + if (root is null) + { + check("architecture: repository root found", false, + "walked up from " + AppContext.BaseDirectory + + " without finding a directory that contains Cargo.toml and apps"); + return; + } + + CheckLayerDirections(check, root); + CheckViewModelSources(check, root); + CheckProjectGraphAcyclic(check, root); + CheckCorePurity(check, root); + CheckFfiPurity(check, root); + SelfProof(check, writableRoot); + } + + private static string? FindRepoRoot() + { + DirectoryInfo? dir = new(AppContext.BaseDirectory); + while (dir is not null) + { + if (File.Exists(Path.Combine(dir.FullName, "Cargo.toml")) && + Directory.Exists(Path.Combine(dir.FullName, "apps"))) + { + return dir.FullName; + } + dir = dir.Parent; + } + return null; + } + + private static void CheckLayerDirections(TestCheck check, string root) + { + string core = File.ReadAllText( + Path.Combine(root, "apps", "windows", "Keepassity.Core", "Keepassity.Core.csproj")); + check("architecture: Core does not reference ViewModels or App", + !core.Contains("Keepassity.ViewModels") && !core.Contains("Keepassity.App")); + + string viewModels = File.ReadAllText( + Path.Combine(root, "apps", "windows", "Keepassity.ViewModels", "Keepassity.ViewModels.csproj")); + string[] forbiddenPackages = ["WindowsAppSDK", "Microsoft.WinUI", "WinRT", "H.NotifyIcon"]; + string? leaked = forbiddenPackages.FirstOrDefault(viewModels.Contains); + check("architecture: ViewModels project has no WinUI/WinRT package", + leaked is null, leaked is null ? "" : leaked); + } + + private static void CheckViewModelSources(TestCheck check, string root) + { + string dir = Path.Combine(root, "apps", "windows", "Keepassity.ViewModels"); + string[] forbidden = ["using Microsoft.UI", "using Windows.", "using WinRT", "using Microsoft.Windows"]; + List hits = new(); + foreach (string file in Directory.EnumerateFiles(dir, "*.cs", SearchOption.AllDirectories)) + { + foreach (string line in File.ReadLines(file)) + { + string trimmed = line.TrimStart(); + if (forbidden.Any(trimmed.StartsWith)) + { + hits.Add(Path.GetFileName(file) + ": " + trimmed); + } + } + } + check("architecture: ViewModels sources import no WinUI/WinRT namespace", + hits.Count == 0, string.Join("; ", hits.Take(3))); + } + + private static void CheckProjectGraphAcyclic(TestCheck check, string root) + { + string apps = Path.Combine(root, "apps", "windows"); + if (!Directory.Exists(apps)) + { + check("architecture: project reference graph has no cycle", false, + "missing " + apps); + return; + } + var projects = Directory.EnumerateFiles(apps, "*.csproj", SearchOption.AllDirectories) + .ToDictionary(p => Path.GetFullPath(p), StringComparer.OrdinalIgnoreCase); + var edges = projects.ToDictionary( + p => p.Key, _ => new List(), StringComparer.OrdinalIgnoreCase); + foreach (var (project, _) in projects) + { + string text = File.ReadAllText(project); + foreach (Match m in Regex.Matches(text, "ProjectReference\\s+Include=\"([^\"]+)\"")) + { + string resolved = Path.GetFullPath( + Path.Combine(Path.GetDirectoryName(project)!, m.Groups[1].Value)); + if (projects.ContainsKey(resolved)) + { + edges[project].Add(resolved); + } + } + } + + var state = new Dictionary(); // 0 unvisited, 1 open, 2 done + bool cycle = false; + foreach (string node in projects.Keys) + { + if (Visit(node)) + { + cycle = true; + break; + } + } + bool Visit(string node) + { + switch (state.GetValueOrDefault(node)) + { + case 1: return true; // back edge + case 2: return false; + } + state[node] = 1; + foreach (string next in edges[node]) + { + if (Visit(next)) return true; + } + state[node] = 2; + return false; + } + check("architecture: project reference graph has no cycle", !cycle); + } + + private static void CheckCorePurity(TestCheck check, string root) + { + string core = Path.Combine(root, "crates", "core", "src"); + if (!Directory.Exists(core)) + { + check("architecture: crates/core stays free of IO, network and environment", + false, "missing " + core); + return; + } + string[] forbidden = ["std::fs", "std::net", "std::env", "std::process", + "reqwest", "tokio", "ureq"]; + List hits = new(); + foreach (string file in Directory.EnumerateFiles(core, "*.rs", SearchOption.AllDirectories)) + { + string[] lines = File.ReadAllLines(file); + bool[] inTest = TestModuleMask(lines); + for (int i = 0; i < lines.Length; i++) + { + if (inTest[i]) continue; + string code = StripRustNoise(lines[i]); + string? hit = forbidden.FirstOrDefault(code.Contains); + if (hit is not null) + { + hits.Add(Path.GetRelativePath(root, file) + ":" + (i + 1) + " " + hit); + } + } + } + check("architecture: crates/core stays free of IO, network and environment", + hits.Count == 0, string.Join("; ", hits.Take(3))); + } + + private static void CheckFfiPurity(TestCheck check, string root) + { + string ffi = Path.Combine(root, "crates", "ffi", "src"); + if (!Directory.Exists(ffi)) + { + check("architecture: crates/ffi does no network or environment access", + false, "missing " + ffi); + return; + } + List hard = new(); + int fsLines = 0; + foreach (string file in Directory.EnumerateFiles(ffi, "*.rs", SearchOption.AllDirectories)) + { + string[] lines = File.ReadAllLines(file); + bool[] inTest = TestModuleMask(lines); + for (int i = 0; i < lines.Length; i++) + { + if (inTest[i]) continue; + string code = StripRustNoise(lines[i]); + if (code.Contains("std::net") || code.Contains("std::env")) + { + hard.Add(Path.GetRelativePath(root, file) + ":" + (i + 1)); + } + if (code.Contains("std::fs")) + { + fsLines++; + } + } + } + check("architecture: crates/ffi does no network or environment access", + hard.Count == 0, string.Join("; ", hard.Take(3))); + // std::fs is tolerated only for the CSPRNG entropy fallback in lib.rs + // (reading /dev/urandom on unix); more uses must go through the core. + check("architecture: crates/ffi std::fs stays within the entropy fallback", + fsLines <= 3, "std::fs lines=" + fsLines + " cap=3"); + } + + /// + /// Runs every detector against a synthetic tree that violates each rule and + /// verifies the detector reports it red. Proves the real-tree green above is + /// a passing assertion, not a detector that silently cannot fail. + /// + private static void SelfProof(TestCheck check, string writableRoot) + { + string tmp = Path.Combine(writableRoot, "arch-selfproof-" + Guid.NewGuid().ToString("N")); + var log = new List<(string Name, bool Ok)>(); + void Capture(string name, bool ok, string detail = "") => log.Add((name, ok)); + bool Red(string prefix) => + log.Any(e => e.Name.StartsWith(prefix, StringComparison.Ordinal) && !e.Ok); + + try + { + string apps = Path.Combine(tmp, "apps", "windows"); + Directory.CreateDirectory(Path.Combine(apps, "Keepassity.Core")); + Directory.CreateDirectory(Path.Combine(apps, "Keepassity.ViewModels")); + File.WriteAllText(Path.Combine(apps, "Keepassity.Core", "Keepassity.Core.csproj"), + ""); + File.WriteAllText(Path.Combine(apps, "Keepassity.ViewModels", "Keepassity.ViewModels.csproj"), + ""); + CheckLayerDirections(Capture, tmp); + check("architecture self-proof: csproj reference direction detected", + Red("architecture: Core does not reference")); + + Directory.CreateDirectory(apps); + File.WriteAllText(Path.Combine(apps, "Keepassity.ViewModels", "Keepassity.ViewModels.csproj"), + ""); + File.WriteAllText(Path.Combine(apps, "Keepassity.ViewModels", "Bad.cs"), + "using Microsoft.UI.Xaml;\n"); + CheckViewModelSources(Capture, tmp); + check("architecture self-proof: ViewModels WinUI import detected", + Red("architecture: ViewModels sources import")); + + string appDir = Path.Combine(apps, "Keepassity.App"); + Directory.CreateDirectory(appDir); + File.WriteAllText(Path.Combine(appDir, "Keepassity.App.csproj"), + ""); + File.WriteAllText(Path.Combine(apps, "Keepassity.Core", "Keepassity.Core.csproj"), + ""); + File.WriteAllText(Path.Combine(apps, "Keepassity.ViewModels", "Keepassity.ViewModels.csproj"), + ""); + CheckProjectGraphAcyclic(Capture, tmp); + check("architecture self-proof: reference cycle detected", + Red("architecture: project reference graph")); + + string coreSrc = Path.Combine(tmp, "crates", "core", "src"); + Directory.CreateDirectory(coreSrc); + File.WriteAllText(Path.Combine(coreSrc, "lib.rs"), + "#[cfg(test)]\nmod tests {\n use std::fs;\n}\nuse std::env;\n"); + CheckCorePurity(Capture, tmp); + check("architecture self-proof: core IO outside test module detected", + Red("architecture: crates/core stays free of")); + + string ffiSrc = Path.Combine(tmp, "crates", "ffi", "src"); + Directory.CreateDirectory(ffiSrc); + File.WriteAllText(Path.Combine(ffiSrc, "lib.rs"), + "use std::net;\nuse std::fs;\nuse std::fs;\nuse std::fs;\nuse std::fs;\n"); + CheckFfiPurity(Capture, tmp); + check("architecture self-proof: ffi network access detected", + Red("architecture: crates/ffi does no network")); + check("architecture self-proof: ffi std::fs overrun detected", + Red("architecture: crates/ffi std::fs stays")); + } + finally + { + try { Directory.Delete(tmp, recursive: true); } catch { } + } + } + + /// Marks lines that sit inside a `#[cfg(test)]` module. + private static bool[] TestModuleMask(string[] lines) + { + var mask = new bool[lines.Length]; + var testDepths = new Stack(); + bool pending = false; + int depth = 0; + for (int i = 0; i < lines.Length; i++) + { + string line = lines[i]; + if (line.Contains("#[cfg(test)]")) pending = true; + mask[i] = pending || testDepths.Count > 0; + string code = StripRustNoise(line); + foreach (char ch in code) + { + if (ch == '{') + { + if (pending) + { + testDepths.Push(depth); + pending = false; + } + depth++; + } + else if (ch == '}') + { + depth--; + if (testDepths.Count > 0 && depth == testDepths.Peek()) + { + testDepths.Pop(); + } + } + } + } + return mask; + } + + /// Removes string literals and comments so brace counting and + /// token scans do not trip over prose. + private static string StripRustNoise(string line) + { + string noBlock = Regex.Replace(line, "/\\*.*?\\*/", " "); + int comment = noBlock.IndexOf("//", StringComparison.Ordinal); + if (comment >= 0) noBlock = noBlock[..comment]; + return Regex.Replace(noBlock, "\"(\\\\.|[^\"\\\\])*\"", "\"\""); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/AtomicFileTests.cs b/tests/app-core/Keepassity.Core.Tests/AtomicFileTests.cs new file mode 100644 index 0000000..8c5e454 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/AtomicFileTests.cs @@ -0,0 +1,189 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// Durable replacement contract: write-through temporary file, backup, atomic +/// replace, no stray temporary or .bak files, and an empty payload is refused +/// without touching the live file. +/// +internal static class AtomicFileTests +{ + public static void Run(TestCheck check, string rootDirectory) + { + string directory = Path.Combine(rootDirectory, "atomic-file"); + Directory.CreateDirectory(directory); + string path = Path.Combine(directory, "vault.kdbx"); + byte[] first = "first-version"u8.ToArray(); + byte[] second = "second-version"u8.ToArray(); + + AtomicFile.Replace(path, first, backupRetention: 5, reason: "test"); + check("atomic write creates the file", File.Exists(path) && + File.ReadAllBytes(path).SequenceEqual(first)); + check("atomic write leaves no temporary file", + Directory.GetFiles(directory, "*.keepassity-tmp-*").Length == 0, + string.Join(", ", Directory.GetFiles(directory))); + + AtomicFile.Replace(path, second, backupRetention: 5, reason: "test"); + check("atomic replace writes the new bytes", + File.ReadAllBytes(path).SequenceEqual(second)); + check("atomic replace leaves no .bak file", + Directory.GetFiles(directory, "*.keepassity-bak").Length == 0); + check("atomic replace leaves no temporary file after replace", + Directory.GetFiles(directory, "*.keepassity-tmp-*").Length == 0); + List backups = BackupService.ListBackups(path); + check("atomic replace backs up the previous bytes", backups.Count == 1 && + File.ReadAllBytes(backups[0].Path).SequenceEqual(first), + backups.Count.ToString()); + + bool emptyRejected = false; + try + { + AtomicFile.Replace(path, Array.Empty(), 5, "test"); + } + catch (ArgumentException) + { + emptyRejected = true; + } + check("atomic replace refuses an empty payload", emptyRejected); + check("refused atomic replace keeps the live bytes", + File.ReadAllBytes(path).SequenceEqual(second)); + + string config = Path.Combine(directory, "settings.json"); + byte[] firstConfig = "{\"theme\":\"Light\"}"u8.ToArray(); + byte[] secondConfig = "{\"theme\":\"Dark\"}"u8.ToArray(); + AtomicFile.Write(config, firstConfig); + check("atomic config write creates the file", + File.ReadAllBytes(config).SequenceEqual(firstConfig)); + AtomicFile.Write(config, secondConfig); + check("atomic config write replaces the file", + File.ReadAllBytes(config).SequenceEqual(secondConfig)); + check("atomic config write leaves no backup or temporary file", + Directory.GetFiles(directory, "*.keepassity-bak").Length == 0 && + Directory.GetFiles(directory, "*.keepassity-tmp-*").Length == 0); + + string created = Path.Combine(directory, "created.kdbx"); + byte[] createdBytes = "new-database"u8.ToArray(); + AtomicFile.WriteNew(created, createdBytes); + check("create-only write creates the file", + File.ReadAllBytes(created).SequenceEqual(createdBytes)); + check("create-only write leaves no temporary file", + Directory.GetFiles(directory, "created.kdbx.keepassity-tmp-*").Length == 0); + File.WriteAllBytes(created, "existing"u8.ToArray()); + bool createOnlyRefused = false; + try + { + AtomicFile.WriteNew(created, "replacement"u8.ToArray()); + } + catch (IOException) + { + createOnlyRefused = true; + } + check("create-only write refuses an existing file", createOnlyRefused); + check("a refused create-only write keeps the existing bytes", + File.ReadAllBytes(created).SequenceEqual("existing"u8.ToArray())); + check("a refused create-only write leaves no temporary file", + Directory.GetFiles(directory, "created.kdbx.keepassity-tmp-*").Length == 0); + + string live = Path.Combine(directory, "vault.kdbx"); + File.WriteAllBytes(live, "live"u8.ToArray()); + string temp = live + AtomicFile.TempInfix + "abc"; + string legacy = Path.Combine(directory, ".vault.kdbx" + AtomicFile.TempInfix + "old"); + string other = Path.Combine(directory, "other.kdbx" + AtomicFile.TempInfix + "x"); + File.WriteAllBytes(temp, "partial"u8.ToArray()); + File.WriteAllBytes(legacy, "partial"u8.ToArray()); + File.WriteAllBytes(other, "unrelated"u8.ToArray()); + int removed = AtomicFile.CleanupResidualTemps(live); + check("residual save temps are removed", removed == 2 && !File.Exists(temp) && + !File.Exists(legacy), removed.ToString()); + check("residual cleanup keeps the live database", + File.Exists(live) && File.ReadAllBytes(live).SequenceEqual("live"u8.ToArray())); + check("residual cleanup keeps another database's temp", + File.Exists(other), other); + + string copySource = Path.Combine(directory, "copy-source.bin"); + string copyTarget = Path.Combine(directory, "copy-target.bin"); + File.WriteAllBytes(copySource, "conflict-copy"u8.ToArray()); + AtomicFile.Copy(copySource, copyTarget); + check("atomic copy writes the source bytes", + File.ReadAllBytes(copyTarget).SequenceEqual("conflict-copy"u8.ToArray())); + check("atomic copy leaves no temporary file", + Directory.GetFiles(directory, "copy-target.bin.keepassity-tmp-*").Length == 0); + + // File.Replace is unavailable on FAT/exFAT and some network shares; the + // same-volume rename fallback must still place the bytes and leave no + // temporary file behind. + string fallbackTarget = Path.Combine(directory, "fallback.kdbx"); + byte[] fallbackOld = "old-bytes"u8.ToArray(); + byte[] fallbackNew = "new-bytes"u8.ToArray(); + File.WriteAllBytes(fallbackTarget, fallbackOld); + string fallbackTemp = fallbackTarget + AtomicFile.TempInfix + "fallback"; + File.WriteAllBytes(fallbackTemp, fallbackNew); + AtomicFile.ReplaceFlushedTemp(fallbackTemp, fallbackTarget, allowFileReplace: false); + check("replace fallback writes the new bytes", + File.ReadAllBytes(fallbackTarget).SequenceEqual(fallbackNew)); + check("replace fallback leaves no temporary file", !File.Exists(fallbackTemp)); + string createdTarget = Path.Combine(directory, "fallback-created.kdbx"); + string createdTemp = createdTarget + AtomicFile.TempInfix + "created"; + File.WriteAllBytes(createdTemp, fallbackNew); + AtomicFile.ReplaceFlushedTemp(createdTemp, createdTarget, allowFileReplace: false); + check("replace fallback creates a missing destination", + File.ReadAllBytes(createdTarget).SequenceEqual(fallbackNew) && + !File.Exists(createdTemp)); + + string restoreTemp = Path.Combine(directory, ".vault.kdbx.restore-tmp-crash"); + File.WriteAllBytes(restoreTemp, "restore"u8.ToArray()); + AtomicFile.CleanupResidualTemps(live); + check("residual cleanup removes a crash-left restore temporary", + !File.Exists(restoreTemp), restoreTemp); + + string residueRoot = Path.Combine(directory, "app-data"); + string nested = Path.Combine(residueRoot, "state"); + Directory.CreateDirectory(nested); + string staleSave = Path.Combine(residueRoot, "settings.json.keepassity-tmp-dead"); + string staleBackup = Path.Combine(nested, ".2026-01-01.vault.kdbx.tmp-dead"); + string staleRestore = Path.Combine(nested, ".vault.kdbx.restore-tmp-dead"); + string fresh = Path.Combine(nested, "recent-databases.json.keepassity-tmp-live"); + string unrelated = Path.Combine(residueRoot, "settings.json"); + File.WriteAllText(staleSave, "x"); + File.WriteAllText(staleBackup, "x"); + File.WriteAllText(staleRestore, "x"); + File.WriteAllText(fresh, "x"); + File.WriteAllText(unrelated, "{}"); + foreach (string stale in new[] { staleSave, staleBackup, staleRestore }) + { + File.SetLastWriteTimeUtc(stale, DateTime.UtcNow.AddDays(-2)); + } + int treeRemoved = AtomicFile.CleanupResidualTempsInTree(residueRoot, + TimeSpan.FromDays(1)); + check("application-data cleanup removes stale save/restore/backup temporaries", + treeRemoved == 3 && !File.Exists(staleSave) && !File.Exists(staleBackup) && + !File.Exists(staleRestore), treeRemoved.ToString()); + check("application-data cleanup keeps fresh temporaries and real files", + File.Exists(fresh) && File.Exists(unrelated) && + File.ReadAllText(unrelated) == "{}"); + + string guarded = Path.Combine(directory, "guarded.kdbx"); + byte[] guardedOld = "guard-old"u8.ToArray(); + File.WriteAllBytes(guarded, guardedOld); + bool aborted = false; + try + { + AtomicFile.Replace(guarded, "guard-new"u8.ToArray(), backupRetention: 5, + reason: "test", changedBeforeReplace: () => true); + } + catch (CoreException ex) + { + aborted = ex.Code == "VaultChanged"; + } + check("replace guard aborts without touching a changed database", + aborted && File.ReadAllBytes(guarded).SequenceEqual(guardedOld) && + Directory.GetFiles(directory, "guarded.kdbx.keepassity-tmp-*").Length == 0, + aborted.ToString()); + AtomicFile.Replace(guarded, "guard-new"u8.ToArray(), backupRetention: 5, + reason: "test", changedBeforeReplace: () => false); + check("replace guard proceeds when the database is unchanged", + File.ReadAllBytes(guarded).SequenceEqual("guard-new"u8.ToArray())); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/BackupServiceTests.cs b/tests/app-core/Keepassity.Core.Tests/BackupServiceTests.cs index 308e55f..38a8b4d 100644 --- a/tests/app-core/Keepassity.Core.Tests/BackupServiceTests.cs +++ b/tests/app-core/Keepassity.Core.Tests/BackupServiceTests.cs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-or-later using System.Globalization; -using Keepassity.Mock; +using Keepassity.Core; namespace Keepassity.CoreTests; @@ -24,8 +24,55 @@ public static void Run(TestCheck check, string rootDirectory) RunRetentionBoundary(check, rootDirectory); RunDefaultRetention(check, rootDirectory); RunRetentionClamp(check, rootDirectory); + RunTimestampOrdering(check, rootDirectory); RunRestore(check, rootDirectory); RunCorruptedRestoreRejected(check, rootDirectory); + RunResidualTempCleanup(check, rootDirectory); + RunRestoreGuard(check, rootDirectory); + } + + private static void RunRestoreGuard(TestCheck check, string root) + { + string directory = NewDirectory(root, "backup-restore-guard"); + string database = Path.Combine(directory, "vault.kdbx"); + byte[] original = File.ReadAllBytes(TestEnvironment.Fixture(FixtureName)); + byte[] restored = File.ReadAllBytes(TestEnvironment.Fixture("test_db_few_rounds.kdbx")); + File.WriteAllBytes(database, original); + + bool aborted = false; + try + { + BackupService.RestoreBytes(database, restored, + changedBeforeReplace: () => true); + } + catch (CoreException ex) + { + aborted = ex.Code == "VaultChanged"; + } + check("restore guard aborts without touching a changed database", + aborted && File.ReadAllBytes(database).SequenceEqual(original) && + Directory.GetFiles(directory, ".vault.kdbx.restore-tmp-*").Length == 0, + aborted.ToString()); + check("restore guard leaves a pre-restore backup as the recovery point", + BackupService.ListBackups(database).Count >= 1); + } + + private static void RunResidualTempCleanup(TestCheck check, string root) + { + string directory = NewDirectory(root, "backup-residual-temps"); + string database = Path.Combine(directory, "vault.kdbx"); + File.WriteAllBytes(database, File.ReadAllBytes(TestEnvironment.Fixture(FixtureName))); + string backupDirectory = BackupService.BackupDirectory(database); + Directory.CreateDirectory(backupDirectory); + string stale = Path.Combine(backupDirectory, ".2026-01-01.vault.kdbx.tmp-dead"); + string fresh = Path.Combine(backupDirectory, ".2026-01-01.vault.kdbx.tmp-live"); + File.WriteAllText(stale, "x"); + File.WriteAllText(fresh, "x"); + File.SetLastWriteTimeUtc(stale, DateTime.UtcNow.AddDays(-2)); + + int removed = BackupService.CleanupResidualTemps(database, TimeSpan.FromHours(1)); + check("backup cleanup removes a crash-left temporary and keeps a fresh one", + removed == 1 && !File.Exists(stale) && File.Exists(fresh), removed.ToString()); } private static void RunRetentionBoundary(TestCheck check, string root) @@ -40,16 +87,14 @@ private static void RunRetentionBoundary(TestCheck check, string root) for (int index = 0; index < retention + 3; index++) { File.SetLastWriteTime(database, baseTime.AddMinutes(index)); - BackupEntry? backup = BackupService.CreateBackup(database, retention); + BackupEntry? backup = BackupService.CreateBackup(database, retention, + timestamp: baseTime.AddMinutes(index)); check($"retention: backup {index + 1} created", backup is not null); if (backup is null) { return; } created.Add(backup.Path); - // File.Copy may preserve the source timestamp, so pin each backup's - // LastWriteTime to make the pruning order deterministic. - File.SetLastWriteTime(backup.Path, baseTime.AddMinutes(index)); int count = BackupService.ListBackups(database).Count; check($"retention: at most {retention} backups kept after {index + 1} create(s)", count == Math.Min(index + 1, retention), @@ -71,6 +116,11 @@ private static void RunRetentionBoundary(TestCheck check, string root) .All(pair => pair.First.Timestamp >= pair.Second.Timestamp)); check("retention: backup files copy the database bytes", listed.All(entry => File.ReadAllBytes(entry.Path).SequenceEqual(content))); + string backupDirectory = BackupService.BackupDirectory(database); + check("retention: no temporary backup files are left", + Directory.GetFiles(backupDirectory, "*.tmp-*").Length == 0, + string.Join(", ", Directory.GetFiles(backupDirectory, "*.tmp-*") + .Select(Path.GetFileName))); } private static void RunDefaultRetention(TestCheck check, string root) @@ -84,14 +134,14 @@ private static void RunDefaultRetention(TestCheck check, string root) for (int index = 0; index <= DefaultRetention; index++) { File.SetLastWriteTime(database, baseTime.AddMinutes(index)); - BackupEntry? backup = BackupService.CreateBackup(database); + BackupEntry? backup = BackupService.CreateBackup(database, + timestamp: baseTime.AddMinutes(index)); check($"default retention: backup {index + 1} created", backup is not null); if (backup is null) { return; } created.Add(backup.Path); - File.SetLastWriteTime(backup.Path, baseTime.AddMinutes(index)); } List listed = BackupService.ListBackups(database); check("default retention: keeps 20 backups", @@ -116,11 +166,8 @@ private static void RunRetentionClamp(TestCheck check, string root) { File.SetLastWriteTime(database, baseTime.AddMinutes(index)); // Retention values below one are clamped to one backup, never zero. - BackupEntry? backup = BackupService.CreateBackup(database, retention: 0); - if (backup is not null) - { - File.SetLastWriteTime(backup.Path, baseTime.AddMinutes(index)); - } + BackupEntry? backup = BackupService.CreateBackup(database, retention: 0, + timestamp: baseTime.AddMinutes(index)); check("retention: value below one is clamped to a single backup", BackupService.ListBackups(database).Count == 1, BackupService.ListBackups(database).Count.ToString( @@ -128,6 +175,35 @@ private static void RunRetentionClamp(TestCheck check, string root) } } + private static void RunTimestampOrdering(TestCheck check, string root) + { + string directory = NewDirectory(root, "backup-timestamp-ordering"); + string database = Path.Combine(directory, "vault.kdbx"); + File.WriteAllBytes(database, + File.ReadAllBytes(TestEnvironment.Fixture(FixtureName))); + // A source file can carry a future timestamp (clock skew, copied vault). + // Retention must follow the backup creation timestamp, not the copied + // file's LastWriteTime, or the newest backup can be pruned immediately. + File.SetLastWriteTime(database, new DateTime(2035, 1, 1, 0, 0, 0, + DateTimeKind.Local)); + DateTimeOffset created = new(new DateTime(2026, 5, 6, 7, 8, 9, 123, + DateTimeKind.Local)); + BackupEntry? backup = BackupService.CreateBackup(database, retention: 1, + timestamp: created); + check("timestamp ordering: backup created despite a future source mtime", + backup is not null); + if (backup is null) + { + return; + } + check("timestamp ordering: backup time comes from its name", + Math.Abs((backup.Timestamp - created).TotalSeconds) < 1, + backup.Timestamp.ToString("O", CultureInfo.InvariantCulture)); + check("timestamp ordering: retention keeps the new backup", + File.Exists(backup.Path) && + BackupService.ListBackups(database).Count == 1); + } + private static void RunRestore(TestCheck check, string root) { string directory = NewDirectory(root, "backup-restore"); @@ -191,6 +267,20 @@ beforeRestore is not null && missingRejected = true; } check("restore: missing backup file is rejected", missingRejected); + + bool emptyRejected = false; + byte[] liveBeforeEmpty = File.ReadAllBytes(database); + try + { + BackupService.RestoreBytes(database, Array.Empty(), DefaultRetention); + } + catch (ArgumentException) + { + emptyRejected = true; + } + check("restore: empty backup content is rejected", emptyRejected); + check("restore: rejected empty backup leaves the live database unchanged", + File.ReadAllBytes(database).SequenceEqual(liveBeforeEmpty)); } private static void RunCorruptedRestoreRejected( diff --git a/tests/app-core/Keepassity.Core.Tests/CertificateTrustTests.cs b/tests/app-core/Keepassity.Core.Tests/CertificateTrustTests.cs new file mode 100644 index 0000000..14411ac --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/CertificateTrustTests.cs @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Net.Security; +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// Headless checks for the WebDAV certificate-trust classification +/// (ADR-0035 M7-06). Uses synthetic certificate facts, so no network and no +/// real certificate are involved. +/// +internal static class CertificateTrustTests +{ + private static TlsCertificateInfo Info(string fingerprint, bool publiclyTrusted = false) + { + return new TlsCertificateInfo + { + Host = "dav.example.test", + Port = 443, + Subject = "CN=dav.example.test", + Issuer = "CN=dav.example.test", + Sha256FingerprintHex = fingerprint, + NotAfter = DateTimeOffset.UnixEpoch.AddYears(100), + Errors = publiclyTrusted ? SslPolicyErrors.None : SslPolicyErrors.RemoteCertificateChainErrors, + }; + } + + public static void Run(TestCheck check) + { + // trust key: host and port, not the path + check("cert trust: key is host and port", + CertificateTrust.TrustKey("https://dav.example.test:8443/db/file.kdbx") == + "dav.example.test:8443", + CertificateTrust.TrustKey("https://dav.example.test:8443/db/file.kdbx")); + check("cert trust: default https port is explicit in the key", + CertificateTrust.TrustKey("https://dav.example.test/db.kdbx") == + "dav.example.test:443"); + check("cert trust: another path on the same server keeps the key", + CertificateTrust.TrustKey("https://dav.example.test/other.kdbx") == + CertificateTrust.TrustKey("https://dav.example.test/first.kdbx")); + check("cert trust: an unparsable url is its own key", + CertificateTrust.TrustKey("not a url") == "not a url"); + + // https gating + check("cert trust: https url recognised", + CertificateTrust.IsHttpsAbsolute("https://dav.example.test/x")); + check("cert trust: http url is not https", + !CertificateTrust.IsHttpsAbsolute("http://dav.example.test/x")); + check("cert trust: relative url is not https", + !CertificateTrust.IsHttpsAbsolute("/x/y")); + + var empty = new Dictionary(); + + // publicly trusted needs no prompt and no pin + check("cert trust: publicly trusted certificate is accepted", + CertificateTrust.Decide("https://dav.example.test/x", Info("aa", true), empty) == + CertificateTrustDecision.PubliclyTrusted); + check("cert trust: publicly trusted wins even when a pin exists", + CertificateTrust.Decide("https://dav.example.test/x", Info("aa", true), + new Dictionary { ["dav.example.test:443"] = "bb" }) == + CertificateTrustDecision.PubliclyTrusted); + + // non-https short-circuits regardless of the certificate + check("cert trust: http url never consults the certificate", + CertificateTrust.Decide("http://dav.example.test/x", Info("aa"), empty) == + CertificateTrustDecision.NotHttps); + + // pinned endpoint, same fingerprint + var pinned = new Dictionary { ["dav.example.test:443"] = "aa" }; + check("cert trust: matching pinned fingerprint is accepted", + CertificateTrust.Decide("https://dav.example.test/x", Info("aa"), pinned) == + CertificateTrustDecision.AlreadyTrusted); + check("cert trust: pin comparison is exact case-sensitive hex", + CertificateTrust.Decide("https://dav.example.test/x", Info("AA"), pinned) == + CertificateTrustDecision.PromptChanged); + check("cert trust: pin is scoped to host and port", + CertificateTrust.Decide("https://other.example.test/x", Info("aa"), pinned) == + CertificateTrustDecision.PromptFirstTime); + + // pinned endpoint, different fingerprint + check("cert trust: a changed pinned certificate is reported as a change", + CertificateTrust.Decide("https://dav.example.test/x", Info("bb"), pinned) == + CertificateTrustDecision.PromptChanged); + + // unknown endpoint + check("cert trust: an unseen self-signed endpoint asks for the first time", + CertificateTrust.Decide("https://dav.example.test/x", Info("aa"), empty) == + CertificateTrustDecision.PromptFirstTime); + + // a pin on another path of the same endpoint still counts as pinned + var pinnedOnOtherPath = new Dictionary + { + ["dav.example.test:8443"] = "cc", + }; + check("cert trust: a pin made on another path applies to the endpoint", + CertificateTrust.Decide("https://dav.example.test:8443/elsewhere.kdbx", + Info("cc"), pinnedOnOtherPath) == CertificateTrustDecision.AlreadyTrusted); + check("cert trust: changing the port asks again", + CertificateTrust.Decide("https://dav.example.test:9443/x", Info("cc"), + pinnedOnOtherPath) == CertificateTrustDecision.PromptFirstTime); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/DatabaseSettingsViewModelTests.cs b/tests/app-core/Keepassity.Core.Tests/DatabaseSettingsViewModelTests.cs new file mode 100644 index 0000000..7a53d78 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/DatabaseSettingsViewModelTests.cs @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Headless checks for the database settings page state. +using Keepassity.Core; +using Keepassity.ViewModels; + +namespace Keepassity.CoreTests; + +internal static class DatabaseSettingsViewModelTests +{ + public static void Run(TestCheck check) + { + void Check(string name, bool ok, string detail = "") => check(name, ok, detail); + + var profile = new VaultProfile + { + Uuid = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + Name = "Keywords", + WebDavUrl = "https://dav.example.test/Keywords.kdbx", + WebDavUsername = "alice", + SyncOnSave = true, + BackupRetention = 20, + }; + var info = new DatabaseInfoDto + { + FormatVersion = "4.1", + VaultUuid = profile.Uuid, + Name = "Keywords", + Cipher = "aes256", + Kdf = new KdfInfoDto + { + Type = "aes-kdf", + Rounds = 600_000, + MobileSafe = true, + }, + }; + var kdbx = new DatabaseSettingsDto + { + RecycleBinEnabled = true, + HistoryMaxItems = 10, + HistoryMaxSize = 6 * 1024 * 1024, + }; + + var vm = new DatabaseSettingsViewModel(profile, info, kdbx, + @"C:\vaults\Keywords.kdbx", 24_359, 1_794_757_695, FakeText.Instance); + + Check("database settings: identity is shown", vm.Name == "Keywords" && + vm.UuidText == profile.Uuid, vm.Name); + Check("database settings: format and cipher are factual", + vm.FormatText == "KDBX 4.1 · aes256", vm.FormatText); + Check("database settings: size is human readable", + vm.SizeText == "23.8 KiB", vm.SizeText); + Check("database settings: the last sync is local time", + vm.LastSyncText.StartsWith("Last sync ", StringComparison.Ordinal), + vm.LastSyncText); + Check("database settings: the source is read-only but visible", + vm.HasWebDav && vm.WebDavUrlText.EndsWith("Keywords.kdbx", StringComparison.Ordinal) && + vm.WebDavUsernameText == "alice", vm.WebDavUrlText); + Check("database settings: the encryption summary comes from the header", + vm.Encryption.Summary == "AES-KDF · 600000 rounds", vm.Encryption.Summary); + + Check("database settings: nothing is dirty on open", + !vm.ProfileChanged && !vm.KdbxSettingsChanged); + + // The page binds the Save button and the unsaved hint to these computed + // flags, so every switch has to announce the new value. + var changed = new List(); + vm.PropertyChanged += (_, e) => changed.Add(e.PropertyName); + + vm.RecycleBinEnabled = false; + Check("database settings: a KDBX switch marks the file dirty", + vm.KdbxSettingsChanged); + Check("database settings: the KDBX dirty flag announces itself", + changed.Contains(nameof(DatabaseSettingsViewModel.KdbxSettingsChanged))); + vm.RecycleBinEnabled = true; + Check("database settings: reverting clears the KDBX dirty flag", + !vm.KdbxSettingsChanged); + + vm.HistoryMaxItems = 11; + Check("database settings: the history limit marks the file dirty", + vm.KdbxSettingsChanged); + vm.HistoryMaxItems = 10; + Check("database settings: the restored history limit clears the flag", + !vm.KdbxSettingsChanged); + + vm.BackupRetention = 12; + Check("database settings: the retention marks the profile dirty", + vm.ProfileChanged); + vm.BackupRetention = 20; + Check("database settings: the restored retention clears the flag", + !vm.ProfileChanged); + + vm.SyncOnSave = false; + Check("database settings: the profile dirty flag announces itself", + changed.Contains(nameof(DatabaseSettingsViewModel.ProfileChanged))); + vm.SyncOnSave = true; + + vm.SyncOnSave = false; + Check("database settings: a switch marks the profile dirty", vm.ProfileChanged); + vm.SyncOnSave = true; + Check("database settings: reverting clears the profile dirty flag", !vm.ProfileChanged); + + vm.BackupRetention = 5000; + Check("database settings: retention is clamped to the allowed range", + vm.BackupRetention == 200, vm.BackupRetention.ToString()); + vm.BackupRetention = 5; + vm.ApplyToProfile(); + Check("database settings: applying writes the profile values", + profile.BackupRetention == 5 && profile.SyncOnSave); + + vm.RecycleBinEnabled = false; + Check("database settings: an KDBX switch marks the file dirty", + vm.KdbxSettingsChanged); + vm.HistoryMaxItems = -3; + Check("database settings: history is clamped to zero", + vm.HistoryMaxItems == 0, vm.HistoryMaxItems.ToString()); + vm.HistoryMaxItems = 25; + DatabaseSettingsDto outgoing = vm.ToKdbxSettings(); + Check("database settings: the outgoing settings carry the edits", + !outgoing.RecycleBinEnabled && outgoing.HistoryMaxItems == 25 && + outgoing.HistoryMaxSize == kdbx.HistoryMaxSize, + $"{outgoing.RecycleBinEnabled}/{outgoing.HistoryMaxItems}"); + + var localOnly = new VaultProfile { Uuid = "bbbb", SyncOnSave = false, BackupRetention = 3 }; + var localVm = new DatabaseSettingsViewModel(localOnly, + new DatabaseInfoDto { FormatVersion = "4.0", VaultUuid = "bbbb" }, + new DatabaseSettingsDto { HistoryMaxItems = 10 }, + @"C:\vaults\Other.kdbx", 1024, null, FakeText.Instance); + Check("database settings: a local vault says so", + !localVm.HasWebDav && localVm.WebDavUrlText == "Not configured", + localVm.WebDavUrlText); + Check("database settings: an unnamed vault falls back", + localVm.Name == "Untitled database" && localVm.LastSyncText == "Never synced", + localVm.Name); + Check("database settings: a small file is described in KiB", + localVm.SizeText == "1 KiB", localVm.SizeText); + } + + private sealed class FakeText : IAppText + { + public static readonly FakeText Instance = new(); + + public string T(string english) => english; + + public string T(string format, params object?[] arguments) => + arguments.Length == 0 ? format : string.Format(format, arguments); + + public string TLong(string key, string english) => english; + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/DiagnosticsServiceTests.cs b/tests/app-core/Keepassity.Core.Tests/DiagnosticsServiceTests.cs new file mode 100644 index 0000000..e4ba243 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/DiagnosticsServiceTests.cs @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.IO.Compression; +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// The diagnostics export must stay readable, unique, durable and bounded: no +/// truncated archive under a real name, no collision when two exports happen in +/// the same second, and only the newest archives are kept. +/// +internal static class DiagnosticsServiceTests +{ + public static void Run(TestCheck check, string rootDirectory) + { + ExportWritesAReadableArchive(check, rootDirectory); + RepeatedExportsDoNotCollide(check, rootDirectory); + RetentionKeepsNewest(check, rootDirectory); + StaleTempFilesAreRemoved(check, rootDirectory); + } + + private static void ExportWritesAReadableArchive(TestCheck check, string rootDirectory) + { + string directory = NewDirectory(rootDirectory, "diagnostics-export"); + var settings = new AppSettings + { + Theme = "Light", + LastDatabasePath = @"C:\private\vault.kdbx", + WebDavUrl = "https://private.example/db.kdbx", + WebDavUsername = "alice", + }; + string path = DiagnosticsService.ExportCore(settings, directory, + new DateTimeOffset(2026, 1, 2, 3, 4, 5, TimeSpan.Zero)); + + check("diagnostics: export creates a timestamped archive", + File.Exists(path) && + string.Equals(Path.GetFileName(path), + "keepassity-diagnostics-20260102-030405-000.zip", StringComparison.Ordinal), + Path.GetFileName(path)); + string summary = ReadEntry(path, "summary.txt"); + string snapshot = ReadEntry(path, "settings.json"); + check("diagnostics: summary and settings snapshot are inside the archive", + summary.Contains("Keepassity diagnostics", StringComparison.Ordinal) && + summary.Contains("app version:", StringComparison.Ordinal) && + snapshot.Contains("\"theme\": \"Light\"", StringComparison.Ordinal), + summary.Length.ToString()); + check("diagnostics: the archive never contains database paths, URLs or usernames", + !snapshot.Contains("vault.kdbx", StringComparison.OrdinalIgnoreCase) && + !snapshot.Contains("private.example", StringComparison.OrdinalIgnoreCase) && + !snapshot.Contains("alice", StringComparison.OrdinalIgnoreCase) && + !snapshot.Contains("last_database_path", StringComparison.OrdinalIgnoreCase), + snapshot); + check("diagnostics: a finished export leaves no temporary file", + Directory.GetFiles(directory, "*.tmp").Length == 0); + } + + private static void RepeatedExportsDoNotCollide(TestCheck check, string rootDirectory) + { + string directory = NewDirectory(rootDirectory, "diagnostics-collision"); + var now = new DateTimeOffset(2026, 2, 3, 4, 5, 6, 700, TimeSpan.Zero); + string first = DiagnosticsService.ExportCore(new AppSettings(), directory, now); + string second = DiagnosticsService.ExportCore(new AppSettings(), directory, now); + check("diagnostics: two exports in the same millisecond get distinct names", + !string.Equals(first, second, StringComparison.OrdinalIgnoreCase) && + File.Exists(first) && File.Exists(second), + $"{Path.GetFileName(first)} / {Path.GetFileName(second)}"); + } + + private static void RetentionKeepsNewest(TestCheck check, string rootDirectory) + { + string directory = NewDirectory(rootDirectory, "diagnostics-retention"); + var baseTime = new DateTime(2025, 1, 1, 0, 0, 0, DateTimeKind.Utc); + for (int index = 0; index < 12; index++) + { + string fake = Path.Combine(directory, + $"keepassity-diagnostics-2025{index + 1:00}01-000000-000.zip"); + File.WriteAllBytes(fake, new byte[] { 0x50, 0x4B }); + File.SetLastWriteTimeUtc(fake, baseTime.AddDays(index)); + } + string newest = Path.Combine(directory, + "keepassity-diagnostics-20251201-000000-000.zip"); + File.WriteAllBytes(newest, new byte[] { 0x50, 0x4B }); + File.SetLastWriteTimeUtc(newest, baseTime.AddDays(20)); + + string export = DiagnosticsService.ExportCore(new AppSettings(), directory, + new DateTimeOffset(2026, 5, 1, 0, 0, 0, TimeSpan.Zero)); + string[] archives = Directory.GetFiles(directory, "keepassity-diagnostics-*.zip"); + check("diagnostics: retention keeps only the newest archives", + archives.Length == DiagnosticsService.KeepArchives && File.Exists(export), + archives.Length.ToString()); + check("diagnostics: the oldest archive is removed by retention", + !File.Exists(Path.Combine(directory, + "keepassity-diagnostics-20250101-000000-000.zip"))); + check("diagnostics: the newest pre-existing archive survives retention", + File.Exists(newest)); + } + + private static void StaleTempFilesAreRemoved(TestCheck check, string rootDirectory) + { + string directory = NewDirectory(rootDirectory, "diagnostics-temp"); + string stale = Path.Combine(directory, "keepassity-diagnostics-stale.zip.tmp"); + File.WriteAllBytes(stale, new byte[] { 1, 2, 3 }); + _ = DiagnosticsService.ExportCore(new AppSettings(), directory, + new DateTimeOffset(2026, 6, 1, 0, 0, 0, TimeSpan.Zero)); + check("diagnostics: a crash-left temporary archive is cleaned up", + !File.Exists(stale)); + } + + private static string ReadEntry(string archivePath, string entryName) + { + using FileStream stream = File.OpenRead(archivePath); + using var zip = new ZipArchive(stream, ZipArchiveMode.Read); + ZipArchiveEntry entry = zip.GetEntry(entryName) + ?? throw new InvalidOperationException($"missing {entryName}"); + using var reader = new StreamReader(entry.Open()); + return reader.ReadToEnd(); + } + + private static string NewDirectory(string rootDirectory, string name) + { + string directory = Path.Combine(rootDirectory, + name + "-" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(directory); + return directory; + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/DropAndReplayPolicyTests.cs b/tests/app-core/Keepassity.Core.Tests/DropAndReplayPolicyTests.cs new file mode 100644 index 0000000..ac87e41 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/DropAndReplayPolicyTests.cs @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.ViewModels; + +namespace Keepassity.CoreTests; + +/// +/// Headless checks for the drop-target rules and the network-replay policy +/// (ADR-0035 M7-05). Both were extracted verbatim from the shell; these +/// assertions freeze the decisions the shell used to inline. +/// +internal static class DropAndReplayPolicyTests +{ + public static void Run(TestCheck check) + { + // ---- drop targets ---- + check("drop: kdbx file recognised", DropTargetResolver.IsKdbxFile("vault.kdbx")); + check("drop: kdbx extension is case-insensitive", + DropTargetResolver.IsKdbxFile("VAULT.KDBX")); + check("drop: other extensions rejected", + !DropTargetResolver.IsKdbxFile("vault.txt") && + !DropTargetResolver.IsKdbxFile("vaultkdbx") && + !DropTargetResolver.IsKdbxFile(null) && + !DropTargetResolver.IsKdbxFile("")); + + check("drop: first database file wins among mixed files", + DropTargetResolver.FirstDatabaseFile( + ["notes.txt", "a.keyx", "vault.kdbx", "second.kdbx"]) == "vault.kdbx"); + check("drop: no database file selects nothing", + DropTargetResolver.FirstDatabaseFile(["notes.txt", "photo.png"]) is null); + check("drop: empty drop selects nothing", + DropTargetResolver.FirstDatabaseFile([]) is null); + + check("drop: top-level row resolves to the root group", + DropTargetResolver.ResolveGroupUuid("all", "root-uuid") == "root-uuid"); + check("drop: top-level row without a root group is not a target", + DropTargetResolver.ResolveGroupUuid("all", null) is null && + DropTargetResolver.ResolveGroupUuid("all", "") is null); + check("drop: a normal row resolves to its own tag", + DropTargetResolver.ResolveGroupUuid("group-uuid", "root-uuid") == "group-uuid"); + check("drop: a row without a tag is not a target", + DropTargetResolver.ResolveGroupUuid(null, "root-uuid") is null && + DropTargetResolver.ResolveGroupUuid("", "root-uuid") is null); + + check("drop: the all-entries row is the top level", + DropTargetResolver.IsTopLevelTarget("all")); + check("drop: a normal group is not the top level", + !DropTargetResolver.IsTopLevelTarget("group-uuid") && + !DropTargetResolver.IsTopLevelTarget(null)); + + check("drop: moving onto the row's own group is refused", + DropTargetResolver.IsSameGroupMove("group-uuid", "group-uuid")); + check("drop: a different group is an allowed move", + !DropTargetResolver.IsSameGroupMove("group-a", "group-b")); + check("drop: an unknown source group never counts as the same group", + !DropTargetResolver.IsSameGroupMove(null, "group-b") && + !DropTargetResolver.IsSameGroupMove(null, null)); + + // ---- network replay ---- + check("replay: connectivity event arms the debounce", + NetworkReplayPolicy.ShouldArmDebounce(true, false)); + check("replay: unavailable network does not arm the debounce", + !NetworkReplayPolicy.ShouldArmDebounce(false, false)); + check("replay: a closing window does not arm the debounce", + !NetworkReplayPolicy.ShouldArmDebounce(true, true)); + + check("replay: unconfigured sync does nothing", + NetworkReplayPolicy.Decide(false, true, true, false) == + NetworkReplayDecision.NotConfigured); + check("replay: unconfigured sync wins over a locked vault", + NetworkReplayPolicy.Decide(false, false, false, true) == + NetworkReplayDecision.NotConfigured); + check("replay: a locked vault skips the run", + NetworkReplayPolicy.Decide(true, false, true, false) == + NetworkReplayDecision.VaultLocked); + check("replay: a missing database path skips the run", + NetworkReplayPolicy.Decide(true, true, false, false) == + NetworkReplayDecision.VaultLocked); + check("replay: a busy shell skips the run", + NetworkReplayPolicy.Decide(true, true, true, true) == + NetworkReplayDecision.Busy); + check("replay: a configured idle unlocked vault replays", + NetworkReplayPolicy.Decide(true, true, true, false) == + NetworkReplayDecision.Replay); + check("replay: locked vault wins over busy", + NetworkReplayPolicy.Decide(true, false, false, true) == + NetworkReplayDecision.VaultLocked); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/EncryptionViewModelTests.cs b/tests/app-core/Keepassity.Core.Tests/EncryptionViewModelTests.cs new file mode 100644 index 0000000..07b193f --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/EncryptionViewModelTests.cs @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Headless behaviour checks for the encryption-parameters view model. +using Keepassity.Core; +using Keepassity.ViewModels; + +namespace Keepassity.CoreTests; + +internal static class EncryptionViewModelTests +{ + public static void Run(TestCheck check) + { + void Check(string name, bool ok, string detail = "") => check(name, ok, detail); + + var argon = new DatabaseInfoDto + { + FormatVersion = "4.0", + Cipher = "aes256", + Compression = "gzip", + Kdf = new KdfInfoDto + { + Type = "argon2id", + MemoryKib = 64 * 1024, + MemoryMib = 64, + Iterations = 3, + Parallelism = 2, + Version = 0x13, + MobileSafe = true, + }, + }; + var vm = new EncryptionViewModel(argon, FakeText.Instance); + + Check("encryption shows the header values verbatim", + vm.Summary == "Argon2id · 64 MiB · 3 iterations · 2 lanes", vm.Summary); + Check("encryption matches the current preset", + vm.SelectedId == EncryptionViewModel.KeepassXcPreset, + vm.SelectedId ?? ""); + Check("encryption cannot apply an unchanged preset", !vm.CanApply); + Check("encryption offers four presets", vm.Choices.Count == 4, + vm.Choices.Count.ToString()); + Check("encryption rows carry both columns", + vm.Choices.All(choice => choice.Strength.Length > 0 && + choice.Compatibility.Length > 0 && + choice.Title.Length > 0)); + + vm.Select(EncryptionViewModel.DesktopPreset); + Check("encryption applies a different preset", vm.CanApply, + vm.SelectedId ?? ""); + vm.Select("no-such-preset"); + Check("encryption ignores unknown presets", + vm.SelectedId == EncryptionViewModel.DesktopPreset); + vm.Select(null); + Check("encryption ignores a null selection", + vm.SelectedId == EncryptionViewModel.DesktopPreset); + + var aes = new DatabaseInfoDto + { + FormatVersion = "4.1", + Kdf = new KdfInfoDto { Type = "aes-kdf", Rounds = 600_000, MobileSafe = true }, + }; + var aesVm = new EncryptionViewModel(aes, FakeText.Instance); + Check("encryption describes an AES-KDF header", + aesVm.Summary == "AES-KDF · 600000 rounds", aesVm.Summary); + Check("encryption matches the classic preset", + aesVm.SelectedId == EncryptionViewModel.ClassicPreset, + aesVm.SelectedId ?? ""); + Check("encryption never applies without a change", !aesVm.CanApply); + + var custom = new DatabaseInfoDto + { + FormatVersion = "4.0", + Kdf = new KdfInfoDto + { + Type = "argon2id", + MemoryMib = 100, + Iterations = 5, + Parallelism = 4, + }, + }; + var customVm = new EncryptionViewModel(custom, FakeText.Instance); + Check("encryption reports a custom profile as described", + customVm.Summary == "Argon2id · 100 MiB · 5 iterations · 4 lanes", + customVm.Summary); + Check("encryption does not preselect a custom profile", + customVm.SelectedId is null && !customVm.CanApply); + customVm.Select(EncryptionViewModel.ClassicPreset); + Check("encryption can still switch a custom profile", customVm.CanApply); + + var unknown = new EncryptionViewModel( + new DatabaseInfoDto { FormatVersion = "4.0" }, FakeText.Instance); + Check("encryption states a missing KDF", + unknown.Summary == "Not reported by the file header", unknown.Summary); + Check("encryption has nothing to apply without a KDF", + unknown.SelectedId is null && !unknown.CanApply); + } + + private sealed class FakeText : IAppText + { + public static readonly FakeText Instance = new(); + + public string T(string english) => english; + + public string T(string format, params object?[] arguments) => + arguments.Length == 0 ? format : string.Format(format, arguments); + + public string TLong(string key, string english) => english; + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/EntryDetailViewModelTests.cs b/tests/app-core/Keepassity.Core.Tests/EntryDetailViewModelTests.cs new file mode 100644 index 0000000..1c64915 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/EntryDetailViewModelTests.cs @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.ViewModels; + +namespace Keepassity.CoreTests; + +/// +/// Headless checks for the detail panel's view model: field visibility, divider +/// rules, tag formatting, password masking/reveal and the empty state. +/// +internal static class EntryDetailViewModelTests +{ + public static void Run(TestCheck check) + { + var detail = new EntryDetailViewModel(); + detail.Clear("Select an entry"); + check("detail: empty title", detail.Title == "Select an entry", detail.Title); + check("detail: empty hides every field", + !detail.HasUsername && !detail.HasPassword && !detail.HasUrl && + !detail.HasTags && !detail.HasNotes && !detail.HasCustomField && !detail.HasTotp, + detail.PasswordText); + + detail.Load(new EntryDetailInput( + "GitHub", + "Work", + "alice", + "s3cret", + "https://github.com", + "Recovery codes are stored offline.", + new[] { "work", "2FA" }, + "Recovery email", + "alice@example.com", + true)); + check("detail: title and group", detail.Title == "GitHub" && detail.Subtitle == "Work", + detail.Subtitle); + check("detail: fields", detail.Username == "alice" && + detail.Url == "https://github.com" && + detail.Notes.StartsWith("Recovery"), detail.Url); + check("detail: tags joined", detail.Tags == "work \u00b7 2FA", detail.Tags); + check("detail: custom field", detail.HasCustomField && + detail.CustomFieldName == "Recovery email" && + detail.CustomFieldValue == "alice@example.com", detail.CustomFieldName); + check("detail: all flags", detail.HasUsername && detail.HasPassword && + detail.HasUrl && detail.HasTags && detail.HasNotes && detail.HasTotp); + check("detail: dividers", detail.ShowUsernameDivider && + detail.ShowPasswordDivider && detail.ShowUrlDivider); + check("detail: password starts masked", + detail.PasswordText == new string('\u2022', 12), detail.PasswordText); + int changes = 0; + detail.PropertyChanged += (_, args) => + { + if (args.PropertyName == nameof(EntryDetailViewModel.PasswordText)) + { + changes++; + } + }; + detail.SetPasswordVisible(true); + check("detail: reveal shows the secret", detail.PasswordText == "s3cret", + detail.PasswordText); + detail.SetPasswordVisible(false); + check("detail: hide restores the mask", detail.PasswordText == new string('\u2022', 12)); + check("detail: reveal/hide notify twice", changes == 2, changes.ToString()); + + detail.Load(new EntryDetailInput( + "Minimal", + "Vault", + string.Empty, + "only-password", + string.Empty, + string.Empty, + Array.Empty(), + null, + null, + false)); + check("detail: password-only entry", detail.HasPassword && !detail.HasUsername && + !detail.HasUrl && !detail.HasTags && !detail.HasNotes && !detail.HasCustomField); + check("detail: password-only divider", !detail.ShowUsernameDivider && + !detail.ShowPasswordDivider && !detail.ShowUrlDivider); + check("detail: password-only mask", detail.PasswordText == new string('\u2022', 12)); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/EntryEditorViewModelTests.cs b/tests/app-core/Keepassity.Core.Tests/EntryEditorViewModelTests.cs new file mode 100644 index 0000000..aa94ea2 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/EntryEditorViewModelTests.cs @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.ViewModels; + +namespace Keepassity.CoreTests; + +/// +/// Headless checks for the entry editor's normalization: untitled fallback, +/// tag parsing, TOTP defaults/clamping and the delete-on-empty-secret rule. +/// +internal static class EntryEditorViewModelTests +{ + public static void Run(TestCheck check) + { + check("editor: tags trim and de-duplicate", + EntryEditorViewModel.ParseTags(" work, 2FA,work, , personal ") + .SequenceEqual(new[] { "work", "2FA", "personal" }), + string.Join(",", EntryEditorViewModel.ParseTags(" work, 2FA,work, , personal "))); + + var created = EntryEditorViewModel.New("group-1"); + created.Title = " Bank "; + created.Username = " alice "; + created.Url = " https://example.com "; + check("editor: create title trims", created.CreateTitle("Untitled") == "Bank", + created.CreateTitle("Untitled")); + check("editor: create username trims", created.NormalizedUsername() == "alice"); + check("editor: create URL trims", created.NormalizedUrl() == "https://example.com"); + check("editor: new entry group", created.IsNew && created.GroupUuid == "group-1"); + created.Title = " "; + check("editor: blank title falls back", created.CreateTitle("Untitled") == "Untitled", + created.CreateTitle("Untitled")); + + var edited = EntryEditorViewModel.FromEntry( + "entry-1", + "Old title", + "bob", + "secret", + "https://old.example", + new[] { "a", "b" }, + "notes", + "JBSWY3DPEHPK3PXP", + "SHA256", + 8, + 60); + check("editor: existing entry identity", + !edited.IsNew && edited.Uuid == "entry-1"); + check("editor: existing tags rendered", edited.TagsText == "a, b", edited.TagsText); + check("editor: existing TOTP loaded", edited.HasExistingTotp && + edited.TotpSecret == "JBSWY3DPEHPK3PXP" && edited.TotpAlgorithm == "SHA256" && + edited.TotpDigits == "8" && edited.TotpPeriod == 60, + edited.TotpAlgorithm); + check("editor: existing TOTP builds", edited.BuildTotp() is + { SecretBase32: "JBSWY3DPEHPK3PXP", Algorithm: "SHA256", Digits: 8, Period: 60 }); + + edited.TotpSecret = " "; + check("editor: empty secret deletes existing TOTP", edited.ShouldDeleteTotp); + check("editor: empty secret builds no TOTP", edited.BuildTotp() is null); + + var defaults = EntryEditorViewModel.New("g"); + defaults.TotpSecret = " ABC "; + defaults.TotpAlgorithm = "sha256"; + defaults.TotpDigits = "7"; + defaults.TotpPeriod = 999; + TotpEditorValue? value = defaults.BuildTotp(); + check("editor: TOTP defaults and clamps", + value is { SecretBase32: "ABC", Algorithm: "SHA1", Digits: 6, Period: 300 }, + value?.ToString() ?? "null"); + + defaults.TotpPeriod = 0; + check("editor: TOTP period lower clamp", defaults.BuildTotp()?.Period == 1, + defaults.BuildTotp()?.Period.ToString() ?? "null"); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/EntryListViewModelTests.cs b/tests/app-core/Keepassity.Core.Tests/EntryListViewModelTests.cs new file mode 100644 index 0000000..7526302 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/EntryListViewModelTests.cs @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.ViewModels; + +namespace Keepassity.CoreTests; + +/// +/// Headless checks for the entry-list view models: sorting/filtering/fingerprint +/// and the row's display strings. This is the part of the middle column that no +/// WinUI test would cover. +/// +internal static class EntryListViewModelTests +{ + public static void Run(TestCheck check) + { + var alpha = new EntryRowInput("uuid-a", "g-work", "Work", "Alpha", "alice", + string.Empty, false, 10); + var beta = new EntryRowInput("uuid-b", "g-home", "Home", "beta", string.Empty, + "https://example.com/path", true, 30); + var gamma = new EntryRowInput("uuid-c", "g-work", "Work", "Gamma", "carol", + string.Empty, false, 20); + EntryRowInput[] rows = { alpha, beta, gamma }; + + List byTitle = + EntryListProjection.Visible(rows, EntrySort.Title, false); + check("entry list: title order", byTitle.Select(row => row.Uuid) + .SequenceEqual(new[] { "uuid-a", "uuid-b", "uuid-c" }), + string.Join(",", byTitle.Select(row => row.Title))); + + List byModified = + EntryListProjection.Visible(rows, EntrySort.Modified, false); + check("entry list: modified order", byModified.Select(row => row.Uuid) + .SequenceEqual(new[] { "uuid-b", "uuid-c", "uuid-a" }), + string.Join(",", byModified.Select(row => row.Title))); + + List byGroup = + EntryListProjection.Visible(rows, EntrySort.Group, false); + check("entry list: group then title order", byGroup.Select(row => row.Uuid) + .SequenceEqual(new[] { "uuid-b", "uuid-a", "uuid-c" }), + string.Join(",", byGroup.Select(row => row.GroupName))); + + List totpOnly = + EntryListProjection.Visible(rows, EntrySort.Title, true); + check("entry list: TOTP filter", totpOnly.Count == 1 && totpOnly[0].Uuid == "uuid-b", + totpOnly.Count.ToString()); + + string first = EntryListProjection.Fingerprint(byTitle, "All entries"); + string same = EntryListProjection.Fingerprint(byTitle.ToList(), "All entries"); + string renamed = EntryListProjection.Fingerprint( + new[] { alpha with { Title = "Renamed" }, beta, gamma }, "All entries"); + check("entry list: fingerprint is stable", first == same); + check("entry list: fingerprint notices a rename", first != renamed); + + var row = new EntryRowViewModel(alpha); + check("entry row: title", row.Title == "Alpha", row.Title); + check("entry row: initial", row.Initial == "A", row.Initial); + check("entry row: secondary prefers username", row.Secondary == "alice", + row.Secondary); + check("entry row: avatar color is a hex color", + row.AvatarColor.StartsWith('#') && row.AvatarColor.Length == 7, + row.AvatarColor); + var sameAvatar = new EntryRowViewModel(alpha); + check("entry row: avatar color is stable", row.AvatarColor == sameAvatar.AvatarColor); + + var urlRow = new EntryRowViewModel(beta); + check("entry row: secondary falls back to the URL host", + urlRow.Secondary == "example.com", urlRow.Secondary); + check("entry row: TOTP flag", urlRow.HasTotp); + + var groupOnly = new EntryRowViewModel(gamma with { Username = string.Empty, Url = string.Empty }); + check("entry row: secondary falls back to the group name", + groupOnly.Secondary == "Work", groupOnly.Secondary); + int changes = 0; + groupOnly.PropertyChanged += (_, args) => + { + if (args.PropertyName == nameof(EntryRowViewModel.Secondary)) + { + changes++; + } + }; + groupOnly.UpdateGroup("g-home", "Home"); + check("entry row: move updates group and secondary", + groupOnly.GroupUuid == "g-home" && groupOnly.GroupName == "Home" && + groupOnly.Secondary == "Home" && changes == 1, + $"{groupOnly.GroupName}/{groupOnly.Secondary}/{changes}"); + groupOnly.UpdateGroup("g-home", "Home"); + check("entry row: a no-op move does not notify", changes == 1, changes.ToString()); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/GroupNavigationTests.cs b/tests/app-core/Keepassity.Core.Tests/GroupNavigationTests.cs new file mode 100644 index 0000000..7dce39a --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/GroupNavigationTests.cs @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.ViewModels; + +namespace Keepassity.CoreTests; + +/// +/// Headless checks for the group navigation ordering: special groups pinned, +/// root/blank groups hidden, counts passed through. +/// +internal static class GroupNavigationTests +{ + public static void Run(TestCheck check) + { + var groups = new[] + { + new GroupNavigationInput("root", "Vault"), + new GroupNavigationInput("g1", "Work"), + new GroupNavigationInput("g2", "Templates"), + new GroupNavigationInput("g3", "Personal"), + new GroupNavigationInput("g4", "Recycle Bin"), + new GroupNavigationInput("g5", string.Empty), + }; + List items = GroupNavigationProjection.Build( + groups, + "root", + "All entries", + 9, + uuid => uuid switch { "g1" => 2, "g3" => 1, _ => 0 }, + name => name == "Recycle Bin", + name => name == "Templates"); + check("group nav: all entries first", items[0].Uuid is null && + items[0].Name == "All entries" && items[0].CountValue == 9, + items[0].Name); + check("group nav: normal groups keep vault order", + items.Skip(1).Select(item => item.Uuid) + .SequenceEqual(new[] { "g1", "g3", "g2", "g4" }), + string.Join(",", items.Select(item => item.Name))); + check("group nav: counts", items[1].CountValue == 2 && items[2].CountValue == 1); + check("group nav: root and blank names hidden", + items.All(item => item.Uuid is not ("root" or "g5"))); + check("group nav: templates before recycle bin", + items[^2].Name == "Templates" && items[^1].Name == "Recycle Bin"); + + List empty = GroupNavigationProjection.Build( + Array.Empty(), null, "All entries", 0, + _ => 0, _ => false, _ => false); + check("group nav: empty vault has all entries", empty.Count == 1 && + empty[0].CountValue == 0); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/KdfCommandsTests.cs b/tests/app-core/Keepassity.Core.Tests/KdfCommandsTests.cs new file mode 100644 index 0000000..1064b60 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/KdfCommandsTests.cs @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Wire-shape checks for the set_kdf payloads the app sends to the core. +using System.Text.Json; +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +internal static class KdfCommandsTests +{ + public static void Run(TestCheck check) + { + void Check(string name, bool ok, string detail = "") => check(name, ok, detail); + + string preset = KdfCommands.ForPreset("keepassxc"); + using (JsonDocument document = JsonDocument.Parse(preset)) + { + JsonElement root = document.RootElement; + Check("kdf command: preset payload names the command", + root.GetProperty("command").GetString() == "set_kdf", preset); + Check("kdf command: preset payload carries the preset", + root.GetProperty("preset").GetString() == "keepassxc", preset); + } + + string argon = KdfCommands.ForValues(new KdfInfoDto + { + Type = "argon2id", + MemoryMib = 32, + Iterations = 2, + Parallelism = 3, + }); + using (JsonDocument document = JsonDocument.Parse(argon)) + { + JsonElement kdf = document.RootElement.GetProperty("kdf"); + Check("kdf command: explicit argon2 type", + kdf.GetProperty("type").GetString() == "argon2id", argon); + Check("kdf command: explicit memory in MiB", + kdf.GetProperty("memory_mib").GetInt32() == 32, argon); + Check("kdf command: explicit iterations and lanes", + kdf.GetProperty("iterations").GetInt32() == 2 && + kdf.GetProperty("parallelism").GetInt32() == 3, argon); + } + + string aes = KdfCommands.ForValues(new KdfInfoDto + { + Type = "aes-kdf", + Rounds = 600_000, + }); + using (JsonDocument document = JsonDocument.Parse(aes)) + { + JsonElement kdf = document.RootElement.GetProperty("kdf"); + Check("kdf command: explicit AES-KDF rounds", + kdf.GetProperty("type").GetString() == "aes-kdf" && + kdf.GetProperty("rounds").GetInt32() == 600_000, aes); + } + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/Keepassity.Core.Tests.csproj b/tests/app-core/Keepassity.Core.Tests/Keepassity.Core.Tests.csproj index 9ce0a8b..b24b8c5 100644 --- a/tests/app-core/Keepassity.Core.Tests/Keepassity.Core.Tests.csproj +++ b/tests/app-core/Keepassity.Core.Tests/Keepassity.Core.Tests.csproj @@ -1,12 +1,13 @@ Exe - net8.0 + net10.0 enable enable false + diff --git a/tests/app-core/Keepassity.Core.Tests/LocalizationTests.cs b/tests/app-core/Keepassity.Core.Tests/LocalizationTests.cs new file mode 100644 index 0000000..5a7dd1c --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/LocalizationTests.cs @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// Checks for the runtime language catalog: resolution, fallback, formatting and +/// catalog hygiene (duplicates and composite-format placeholder parity). The UI +/// layer is not referenced here, so these tests also run on CI without WinUI. +/// +internal static class LocalizationTests +{ + public static void Run(Action check) + { + void Check(string name, bool ok, string detail = "") => check(name, ok, detail); + LocalizationCatalog english = LocalizationCatalog.Load( + LocalizationCatalog.EnglishLanguage); + Check("language catalog: English resolves", english.Language == "en", + english.Language); + Check("language catalog: English has no translations", + english.TranslationCount == 0, english.TranslationCount.ToString()); + Check("language catalog: English falls back to the source string", + english.Get("Unlock") == "Unlock", english.Get("Unlock")); + Check("language catalog: English ignores translations", + english.Get("Unlock", "fallback") == "fallback", + english.Get("Unlock", "fallback")); + + LocalizationCatalog chinese = LocalizationCatalog.Load( + LocalizationCatalog.ChineseLanguage); + Check("language catalog: Chinese resolves", chinese.Language == "zh-CN", + chinese.Language); + Check("language catalog: Chinese catalog is not empty", + chinese.TranslationCount > 100, chinese.TranslationCount.ToString()); + Check("language catalog: Chinese translates a known key", + chinese.Get("Settings") == "设置", chinese.Get("Settings")); + Check("language catalog: unknown Chinese key falls back to English", + chinese.Get("This key is not translated") == "This key is not translated", + chinese.Get("This key is not translated")); + Check("language catalog: Chinese honors the explicit fallback", + chinese.Get("Missing.Symbol.Key", "English fallback") == "English fallback", + chinese.Get("Missing.Symbol.Key", "English fallback")); + Check("language catalog: no duplicate keys across catalog files", + chinese.DuplicateKeys.Count == 0, + string.Join(", ", chinese.DuplicateKeys.Take(5))); + Check("language catalog: formatted lookup uses the translation", + chinese.Format("WebDAV: {0}", "https://example.test/db.kdbx") == + "WebDAV:https://example.test/db.kdbx", + chinese.Format("WebDAV: {0}", "https://example.test/db.kdbx")); + + // Every translated sentence must keep exactly the same composite-format + // placeholders as the English key; otherwise string.Format throws or the + // sentence silently loses a value at runtime. + var placeholderMismatches = new List(); + foreach (KeyValuePair entry in chinese.Translations) + { + string keyPlaceholders = Placeholders(entry.Key); + string valuePlaceholders = Placeholders(entry.Value); + if (keyPlaceholders != valuePlaceholders) + { + placeholderMismatches.Add($"{entry.Key} [{keyPlaceholders}] != " + + $"[{valuePlaceholders}]"); + } + } + Check("language catalog: placeholder sets match for every entry", + placeholderMismatches.Count == 0, + string.Join("; ", placeholderMismatches.Take(3))); + + var untranslated = chinese.Translations + .Where(entry => !AllowedIdentical(entry.Key) && + string.Equals(entry.Key, entry.Value, StringComparison.Ordinal)) + .Select(entry => entry.Key) + .ToList(); + Check("language catalog: no unintended untranslated entries", + untranslated.Count == 0, string.Join("; ", untranslated.Take(5))); + + var lowercaseBrand = chinese.Translations + .Where(entry => entry.Key.Contains("keepassity", StringComparison.Ordinal) || + entry.Value.Contains("keepassity", StringComparison.Ordinal)) + .Select(entry => entry.Key) + .ToList(); + check("language catalog: UI text spells the product Keepassity", + lowercaseBrand.Count == 0, string.Join("; ", lowercaseBrand.Take(5))); + + const string systemLanguageCheck = "language resolution: known tags"; + string systemResolved = LocalizationCatalog.NormalizeLanguage("system"); + bool systemMatchesOs = systemResolved == + (System.Globalization.CultureInfo.CurrentUICulture.TwoLetterISOLanguageName + .Equals("zh", StringComparison.OrdinalIgnoreCase) ? "zh-CN" : "en"); + Check(systemLanguageCheck, systemMatchesOs, systemResolved); + Check("language resolution: Chinese variants map to zh-CN", + LocalizationCatalog.NormalizeLanguage("zh-Hans") == "zh-CN" && + LocalizationCatalog.NormalizeLanguage("zh-CN") == "zh-CN" && + LocalizationCatalog.NormalizeLanguage("zh-TW") == "zh-CN"); + Check("language resolution: English variants map to en", + LocalizationCatalog.NormalizeLanguage("en-US") == "en" && + LocalizationCatalog.NormalizeLanguage("EN") == "en"); + Check("language resolution: unsupported languages fall back to English", + LocalizationCatalog.NormalizeLanguage("fr-FR") == "en"); + Check("language resolution: empty setting follows the system", + LocalizationCatalog.NormalizeLanguage(string.Empty) == systemResolved); + } + + private static string Placeholders(string text) + { + var indexes = new SortedSet(); + for (int index = 0; index < text.Length; index++) + { + if (text[index] != '{' || index + 1 >= text.Length) + { + continue; + } + if (text[index + 1] == '{') + { + index++; + continue; + } + int end = text.IndexOf('}', index + 1); + if (end < 0) + { + break; + } + string token = text[(index + 1)..end]; + if (token.Length > 0 && token.All(char.IsDigit) && + int.TryParse(token, out int value)) + { + indexes.Add(value); + } + index = end; + } + return string.Join(",", indexes); + } + + /// Terms that are deliberately identical in both languages. + private static bool AllowedIdentical(string key) + => key is "English" or "TOTP" or "WebDAV" or "KDBX" or "Keepassity" || + key.StartsWith("Keepassity ", StringComparison.Ordinal); +} diff --git a/tests/app-core/Keepassity.Core.Tests/LogFileTests.cs b/tests/app-core/Keepassity.Core.Tests/LogFileTests.cs new file mode 100644 index 0000000..91bfe33 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/LogFileTests.cs @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// The logger must never grow without bound and must never lose a line because +/// another process (or the diagnostics exporter) holds the file: daily files are +/// rotated at a size cap, pruning honours retention and a total-size ceiling, and +/// all handles share read/write/delete. +/// +internal static class LogFileTests +{ + public static void Run(TestCheck check, string rootDirectory) + { + AppendsAndShares(check, rootDirectory); + RotatesAtTheSizeCap(check, rootDirectory); + PrunesOldFilesAndHonoursTotalSize(check, rootDirectory); + } + + private static void AppendsAndShares(TestCheck check, string rootDirectory) + { + string directory = NewDirectory(rootDirectory, "log-append"); + var first = new LogFile(directory); + var second = new LogFile(directory); + DateTimeOffset now = new(2026, 1, 2, 3, 4, 5, TimeSpan.Zero); + first.Append("first writer line", now); + second.Append("second writer line", now); + string path = Path.Combine(directory, "app-20260102.log"); + string content; + using (var reader = new FileStream(path, FileMode.Open, FileAccess.Read, + FileShare.ReadWrite | FileShare.Delete)) + using (var text = new StreamReader(reader)) + { + content = text.ReadToEnd(); + } + check("log: two writers append to the same daily file", + content.Contains("first writer line", StringComparison.Ordinal) && + content.Contains("second writer line", StringComparison.Ordinal), content); + first.Append("readable while a reader is open", now); + second.Append("and the reader still allows writes", now); + check("log: a second append works while a reader holds the file", + File.ReadAllText(path).Contains("still allows writes", StringComparison.Ordinal)); + } + + private static void RotatesAtTheSizeCap(TestCheck check, string rootDirectory) + { + string directory = NewDirectory(rootDirectory, "log-rotate"); + var log = new LogFile(directory, maxFileBytes: 10); + DateTimeOffset now = new(2026, 2, 3, 4, 5, 6, TimeSpan.Zero); + log.Append("1234567890", now); + log.Append("abcdefghij", now); + string path = Path.Combine(directory, "app-20260203.log"); + string rotated = path + ".1"; + check("log: a file that reaches the size cap rotates to one sibling", + File.Exists(rotated) && File.Exists(path), rotated); + check("log: the rotated file keeps the earlier line and the new file the latest", + File.ReadAllText(rotated).Contains("1234567890", StringComparison.Ordinal) && + !File.ReadAllText(rotated).Contains("abcdefghij", StringComparison.Ordinal) && + File.ReadAllText(path).Contains("abcdefghij", StringComparison.Ordinal)); + log.Append("third line", now); + check("log: rotation keeps at most one sibling", + Directory.GetFiles(directory, "app-*.log.1").Length == 1, + string.Join(", ", Directory.GetFiles(directory))); + } + + private static void PrunesOldFilesAndHonoursTotalSize(TestCheck check, + string rootDirectory) + { + string directory = NewDirectory(rootDirectory, "log-prune"); + var log = new LogFile(directory); + DateTimeOffset now = new(2026, 6, 1, 0, 0, 0, TimeSpan.Zero); + string old = Path.Combine(directory, "app-20250101.log"); + string oldRotated = Path.Combine(directory, "app-20250101.log.1"); + string fresh = Path.Combine(directory, "app-20260531.log"); + File.WriteAllText(old, "old"); + File.WriteAllText(oldRotated, "old-rotated"); + File.WriteAllText(fresh, "fresh"); + File.SetLastWriteTimeUtc(old, new DateTime(2025, 1, 1, 0, 0, 0, DateTimeKind.Utc)); + File.SetLastWriteTimeUtc(oldRotated, + new DateTime(2025, 1, 1, 0, 0, 0, DateTimeKind.Utc)); + File.SetLastWriteTimeUtc(fresh, new DateTime(2026, 5, 31, 0, 0, 0, DateTimeKind.Utc)); + + int removed = log.Prune(now, retentionDays: 14); + check("log: pruning removes files past the retention window", + removed == 2 && !File.Exists(old) && !File.Exists(oldRotated) && + File.Exists(fresh), removed.ToString()); + + string sizeDirectory = NewDirectory(rootDirectory, "log-size-cap"); + var sizeLog = new LogFile(sizeDirectory); + var names = new List(); + for (int index = 0; index < 3; index++) + { + string name = Path.Combine(sizeDirectory, $"app-2026060{index + 1}.log"); + File.WriteAllBytes(name, new byte[100]); + File.SetLastWriteTimeUtc(name, + new DateTime(2026, 6, index + 1, 0, 0, 0, DateTimeKind.Utc)); + names.Add(name); + } + int sizeRemoved = sizeLog.Prune(now, retentionDays: 365, maxTotalBytes: 150); + check("log: pruning enforces a total-size ceiling from the oldest files", + sizeRemoved == 2 && !File.Exists(names[0]) && !File.Exists(names[1]) && + File.Exists(names[2]), sizeRemoved.ToString()); + } + + private static string NewDirectory(string rootDirectory, string name) + { + string directory = Path.Combine(rootDirectory, + name + "-" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(directory); + return directory; + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/NewDatabasePreparerTests.cs b/tests/app-core/Keepassity.Core.Tests/NewDatabasePreparerTests.cs new file mode 100644 index 0000000..3dd267f --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/NewDatabasePreparerTests.cs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// Creating a database must use the same durability rules as a save: a local +/// create is flushed and create-only, and a WebDAV create claims the local +/// working copy and its clean baseline only after the remote upload succeeded. +/// +internal static class NewDatabasePreparerTests +{ + public static void Run(TestCheck check, string dataDirectory) + { + LocalCreateIsDurable(check, dataDirectory); + LocalCreateNeverOverwrites(check, dataDirectory); + RemoteCommitWritesWorkingCopyAndBaseline(check, dataDirectory); + RemoteCommitBacksUpAStaleWorkingCopy(check, dataDirectory); + RemoteCommitFailureLeavesNoBaseline(check, dataDirectory); + } + + private static void LocalCreateIsDurable(TestCheck check, string dataDirectory) + { + (string folder, SyncStateStore states) = NewEnvironment(dataDirectory, "local"); + // One level below the environment folder does not exist yet. + string path = Path.Combine(folder, "nested", "vault.kdbx"); + var preparer = new NewDatabasePreparer(states); + byte[] bytes = Bytes(1, 2, 3); + + preparer.CreateLocal(path, bytes); + + check("a new local database is written", + File.Exists(path) && File.ReadAllBytes(path).SequenceEqual(bytes)); + check("a new local database leaves no temporary file", + Directory.GetFiles(Path.GetDirectoryName(path)!, "*keepassity-tmp*").Length == 0); + check("a new local database creates no backup", + BackupService.ListBackups(path).Count == 0); + + bool emptyRejected = false; + try + { + preparer.CreateLocal(Path.Combine(folder, "empty.kdbx"), Array.Empty()); + } + catch (ArgumentException) + { + emptyRejected = true; + } + check("an empty new database is refused", + emptyRejected && !File.Exists(Path.Combine(folder, "empty.kdbx"))); + } + + private static void LocalCreateNeverOverwrites(TestCheck check, string dataDirectory) + { + (string folder, SyncStateStore states) = NewEnvironment(dataDirectory, "no-overwrite"); + string path = Path.Combine(folder, "vault.kdbx"); + File.WriteAllBytes(path, Bytes(9, 9)); + var preparer = new NewDatabasePreparer(states); + + bool refused = false; + try + { + preparer.CreateLocal(path, Bytes(1, 1, 1)); + } + catch (IOException) + { + refused = true; + } + + check("creating a database refuses an existing file", refused); + check("a refused create keeps the existing database", + File.ReadAllBytes(path).SequenceEqual(Bytes(9, 9))); + check("a refused create leaves no temporary file", + Directory.GetFiles(folder, "*keepassity-tmp*").Length == 0); + } + + private static void RemoteCommitWritesWorkingCopyAndBaseline(TestCheck check, + string dataDirectory) + { + (_, SyncStateStore states) = NewEnvironment(dataDirectory, "remote"); + string url = "https://example.test/new-remote.kdbx"; + const string user = "user"; + byte[] bytes = Bytes(4, 5, 6); + var preparer = new NewDatabasePreparer(states); + + string workingCopy = preparer.CommitRemoteAsync(url, user, bytes, "\"etag-new\"", + backupRetention: 5).GetAwaiter().GetResult(); + SyncState state = states.Load(url, user, workingCopy); + + check("a remote create claims the deterministic working copy", + workingCopy == RemoteDatabaseStore.PathFor(url, user) && + File.ReadAllBytes(workingCopy).SequenceEqual(bytes)); + check("a remote create records a clean baseline", + !state.LocalDirty && + state.Etag == "\"etag-new\"" && + state.Sha256 == Sha(bytes) && + state.Size == bytes.Length && + state.RemoteModifiedUnix is null && + state.LastSyncUnix > 0, + state.Sha256 ?? "(none)"); + check("a remote create leaves no temporary file in the working-copy folder", + Directory.GetFiles(Path.GetDirectoryName(workingCopy)!, "*keepassity-tmp*") + .Length == 0); + } + + private static void RemoteCommitBacksUpAStaleWorkingCopy(TestCheck check, + string dataDirectory) + { + (_, SyncStateStore states) = NewEnvironment(dataDirectory, "remote-stale"); + string url = "https://example.test/stale-remote.kdbx"; + const string user = "user"; + byte[] stale = Bytes(1, 1, 1); + byte[] bytes = Bytes(2, 2, 2); + string workingCopy = RemoteDatabaseStore.PathFor(url, user); + Directory.CreateDirectory(Path.GetDirectoryName(workingCopy)!); + File.WriteAllBytes(workingCopy, stale); + var preparer = new NewDatabasePreparer(states); + + preparer.CommitRemoteAsync(url, user, bytes, "\"e1\"").GetAwaiter().GetResult(); + + List backups = BackupService.ListBackups(workingCopy); + check("a remote create backs up a stale working copy", + File.ReadAllBytes(workingCopy).SequenceEqual(bytes) && + backups.Count == 1 && + File.ReadAllBytes(backups[0].Path).SequenceEqual(stale), + backups.Count.ToString()); + } + + private static void RemoteCommitFailureLeavesNoBaseline(TestCheck check, + string dataDirectory) + { + (_, SyncStateStore states) = NewEnvironment(dataDirectory, "remote-failure"); + string url = "https://example.test/failing-remote.kdbx"; + const string user = "user"; + string workingCopy = RemoteDatabaseStore.PathFor(url, user); + // A directory where the working copy should be makes the durable write + // fail after the remote upload already succeeded. + Directory.CreateDirectory(workingCopy); + var preparer = new NewDatabasePreparer(states); + + bool threw = false; + try + { + preparer.CommitRemoteAsync(url, user, Bytes(7, 7), "\"e1\"") + .GetAwaiter().GetResult(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + threw = true; + } + + check("a failed working-copy write is reported", threw); + check("a failed working-copy write leaves no synced baseline", + states.Load(url, user, workingCopy).Sha256 is null && + !states.Load(url, user, workingCopy).LocalDirty); + Directory.Delete(workingCopy); + } + + private static (string Folder, SyncStateStore States) NewEnvironment( + string dataDirectory, string name) + { + string folder = Path.Combine(dataDirectory, + "new-database-" + name + "-" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(folder); + return (folder, new SyncStateStore(Path.Combine(folder, "state"))); + } + + private static byte[] Bytes(params byte[] values) => values; + + private static string Sha(byte[] bytes) + => Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(bytes)) + .ToLowerInvariant(); +} diff --git a/tests/app-core/Keepassity.Core.Tests/Program.cs b/tests/app-core/Keepassity.Core.Tests/Program.cs index e2a9b4d..5762611 100644 --- a/tests/app-core/Keepassity.Core.Tests/Program.cs +++ b/tests/app-core/Keepassity.Core.Tests/Program.cs @@ -3,7 +3,7 @@ // console harness instead of xUnit so it runs without adding test-framework // dependencies; extend it when a real test project is introduced. using Keepassity.CoreTests; -using Keepassity.Mock; +using Keepassity.Core; int failures = 0; void Check(string name, bool ok, string detail = "") @@ -31,6 +31,7 @@ void Check(string name, bool ok, string detail = "") var settings = new AppSettingsStore(); settings.Current.Theme = "Light"; settings.Current.AutoLockMinutes = 42; + settings.Current.Language = "zh-CN"; settings.Save(); var reloaded = new AppSettingsStore(); Check("settings persist theme", @@ -38,9 +39,34 @@ void Check(string name, bool ok, string detail = "") Check("settings persist auto-lock", reloaded.Current.AutoLockMinutes == 42, reloaded.Current.AutoLockMinutes.ToString()); + Check("settings persist UI language", + reloaded.Current.Language == "zh-CN", reloaded.Current.Language); Check("settings schema version", reloaded.Current.SchemaVersion == 1, reloaded.Current.SchemaVersion.ToString()); + // UI language catalog: resolution, fallback, formatting and catalog hygiene. + LocalizationTests.Run(Check); + + // MVVM: the unlock decision path is headless and has its own fakes. + UnlockViewModelTests.Run(Check, dataDirectory); + SyncStatusViewModelTests.Run(Check); + SettingsViewModelTests.Run(Check); + EntryListViewModelTests.Run(Check); + EntryDetailViewModelTests.Run(Check); + EntryEditorViewModelTests.Run(Check); + GroupNavigationTests.Run(Check); + TotpTimingTests.Run(Check); + TotpDisplayViewModelTests.Run(Check); + EncryptionViewModelTests.Run(Check); + KdfCommandsTests.Run(Check); + DatabaseSettingsViewModelTests.Run(Check); + RecentListProjectionTests.Run(Check, dataDirectory); + DropAndReplayPolicyTests.Run(Check); + CertificateTrustTests.Run(Check); + + // architecture: dependency direction and source-tree purity (ADR-0035). + ArchitectureTests.Run(Check, dataDirectory); + // sync state round trip var syncStates = new SyncStateStore(); if (syncStates.Available) @@ -63,6 +89,36 @@ void Check(string name, bool ok, string detail = "") SyncState otherUser = syncStates.Load( "https://example.test/db.kdbx", "other", "/tmp/db.kdbx"); Check("sync state is keyed by user", otherUser.Etag is null); + + // A corrupt or half-written sidecar must fail closed: treating it as + // clean lets the next sync download over local edits. + string corruptUrl = "https://example.test/corrupt.kdbx"; + syncStates.Save(corruptUrl, "user", "/tmp/corrupt.kdbx", + new SyncState + { + Etag = "\"etag\"", + Sha256 = new string('b', 64), + LastSyncUnix = 987654321, + }); + string stateDirectory = Path.Combine(ApplicationPaths.Root, "state"); + string? sidecar = Directory.Exists(stateDirectory) + ? Directory.EnumerateFiles(stateDirectory, "*.json") + .FirstOrDefault(file => File.ReadAllText(file).Contains( + "987654321", StringComparison.Ordinal)) + : null; + Check("sync state sidecar exists for corruption test", sidecar is not null); + if (sidecar is not null) + { + File.WriteAllText(sidecar, "{ not valid json"); + SyncState recovered = syncStates.Load(corruptUrl, "user", "/tmp/corrupt.kdbx"); + Check("corrupt sync state is treated as dirty", recovered.LocalDirty); + } + + syncStates.Save("https://example.test/half.kdbx", "user", "/tmp/half.kdbx", + new SyncState { Etag = "\"etag\"", Sha256 = null }); + SyncState half = syncStates.Load( + "https://example.test/half.kdbx", "user", "/tmp/half.kdbx"); + Check("incomplete sync baseline is treated as dirty", half.LocalDirty); } else { @@ -124,6 +180,7 @@ void Check(string name, bool ok, string detail = "") // M4-01: WebDavClient against an in-process WebDAV mock on a CJK path; also // proves the client sends the percent-encoded request target. WebDavNonAsciiPathTests.Run(Check); + WebDavSafetyTests.Run(Check); WebDavTlsTests.Run(Check); // backups @@ -137,6 +194,24 @@ void Check(string name, bool ok, string detail = "") // M4-05: retention boundary (custom and default 20), restore ordering and // rejection of a corrupted backup with the live database left untouched. BackupServiceTests.Run(Check, dataDirectory); + VaultRecoveryTests.Run(Check, dataDirectory); + AtomicFileTests.Run(Check, dataDirectory); + VaultGuardTests.Run(Check, dataDirectory); + VaultWriteGateTests.Run(Check); + VaultSessionTests.Run(Check, dataDirectory); + VaultFileLockTests.Run(Check, dataDirectory); + RunStateStoreTests.Run(Check, dataDirectory); + RemoteCacheCleanerTests.Run(Check, dataDirectory); + DiagnosticsServiceTests.Run(Check, dataDirectory); + LogFileTests.Run(Check, dataDirectory); + WebDavTimeoutTests.Run(Check); + NewDatabasePreparerTests.Run(Check, dataDirectory); + RecentDatabaseTests.Run(Check, dataDirectory); + SyncStateStoreTests.Run(Check, dataDirectory); + VaultProfileStoreTests.Run(Check, dataDirectory); + RemoteVaultOpenerTests.Run(Check, dataDirectory); + RemoteVaultOpenIntegrationTests.Run(Check, dataDirectory); + SyncCoordinatorTests.Run(Check, dataDirectory); // diagnostics archive contains a summary and no credential blobs string archive = DiagnosticsService.ExportAsync(reloaded.Current) diff --git a/tests/app-core/Keepassity.Core.Tests/RecentDatabaseTests.cs b/tests/app-core/Keepassity.Core.Tests/RecentDatabaseTests.cs new file mode 100644 index 0000000..f48ca4f --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/RecentDatabaseTests.cs @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// Headless checks for the recent-database list: normalization, newest-first +/// order, de-duplication, limit, removal and corrupt-file preservation. +/// +internal static class RecentDatabaseTests +{ + public static void Run(TestCheck check, string rootDirectory) + { + string directory = Path.Combine(rootDirectory, "recent-databases"); + Directory.CreateDirectory(directory); + string path = Path.Combine(directory, "recent.json"); + string vaultA = Path.Combine(directory, "a.kdbx"); + string vaultB = Path.Combine(directory, "b.kdbx"); + string vaultC = Path.Combine(directory, "c.kdbx"); + + var store = new RecentDatabaseStore(path); + store.Remember(vaultA, "local"); + store.Remember(vaultB, "webdav", "https://dav.example.test/b.kdbx", "user"); + store.Remember(vaultA, "local"); + check("recent: newest-first and de-duplicated", + store.Entries.Count == 2 && store.Entries[0].Path == vaultA && + store.Entries[0].Kind == "local" && store.Entries[1].Path == vaultB, + string.Join(", ", store.Entries.Select(entry => entry.DisplayName))); + check("recent: WebDAV facts retained", store.Entries[1].WebDavUrl == + "https://dav.example.test/b.kdbx" && store.Entries[1].WebDavUsername == "user"); + + var reloaded = new RecentDatabaseStore(path); + check("recent: round trips through disk", + reloaded.Entries.Count == 2 && reloaded.Entries[0].Path == vaultA, + reloaded.Entries.Count.ToString()); + + for (int index = 0; index < RecentDatabaseStore.MaxEntries + 2; index++) + { + store.Remember(Path.Combine(directory, $"v{index}.kdbx")); + } + check("recent: list is capped", store.Entries.Count == RecentDatabaseStore.MaxEntries, + store.Entries.Count.ToString()); + check("recent: oldest entries dropped", store.Entries.All(entry => + !string.Equals(entry.Path, Path.GetFullPath(vaultB), + StringComparison.OrdinalIgnoreCase))); + + string toRemove = store.Entries[0].Path; + check("recent: remove reports a hit", store.Remove(toRemove)); + check("recent: remove reports a miss", !store.Remove(toRemove)); + + string corrupt = Path.Combine(directory, "corrupt.json"); + File.WriteAllText(corrupt, "{ not a list"); + var corruptStore = new RecentDatabaseStore(corrupt); + check("recent: corrupt file starts empty", corruptStore.Entries.Count == 0); + check("recent: corrupt file is preserved", + Directory.GetFiles(directory, "corrupt.json.corrupt-*").Length == 1); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/RecentListProjectionTests.cs b/tests/app-core/Keepassity.Core.Tests/RecentListProjectionTests.cs new file mode 100644 index 0000000..7d69f99 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/RecentListProjectionTests.cs @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.Core; +using Keepassity.ViewModels; + +namespace Keepassity.CoreTests; + +/// +/// Headless checks for the recent-database list projection and the +/// accessibility text decisions (ADR-0035 M7-04). The rules were extracted +/// verbatim from the shell; these assertions freeze their current behavior. +/// +internal static class RecentListProjectionTests +{ + public static void Run(TestCheck check, string rootDirectory) + { + string directory = Path.Combine(rootDirectory, "recent-projection"); + Directory.CreateDirectory(directory); + string vaultA = Path.Combine(directory, "a.kdbx"); + + // secondary text: WebDAV entries show the remote URL, local ones the path + var webDav = new RecentDatabaseEntry + { + Path = vaultA, Kind = "webdav", WebDavUrl = "https://dav.example.test/a.kdbx", + }; + check("recent projection: webdav entry shows the remote url", + RecentDatabaseList.SecondaryText(webDav) == "WebDAV · https://dav.example.test/a.kdbx", + RecentDatabaseList.SecondaryText(webDav)); + + var webDavNoUrl = new RecentDatabaseEntry + { + Path = vaultA, Kind = "webdav", WebDavUrl = "", + }; + check("recent projection: webdav entry without url falls back to the path", + RecentDatabaseList.SecondaryText(webDavNoUrl) == vaultA); + + var local = new RecentDatabaseEntry { Path = vaultA, Kind = "local" }; + check("recent projection: local entry shows the path", + RecentDatabaseList.SecondaryText(local) == vaultA); + + // section visibility: only on the start page with something to show + check("recent projection: section hidden while a database is open", + !RecentDatabaseList.SectionVisible(false, 3)); + check("recent projection: section hidden when the list is empty", + !RecentDatabaseList.SectionVisible(true, 0)); + check("recent projection: section visible on the start page with entries", + RecentDatabaseList.SectionVisible(true, 2)); + + // remember classification mirrors the shell's legacy bridge rules + var (kind, url, user) = RecentDatabaseList.RememberArguments(true, null, "user"); + check("recent projection: webdav source without url is remembered local", + kind == "local" && url is null && user is null, + kind + " " + (url ?? "")); + + (kind, url, user) = RecentDatabaseList.RememberArguments(true, "", "user"); + check("recent projection: blank webdav url is remembered local", + kind == "local" && url is null && user is null); + + (kind, url, user) = RecentDatabaseList.RememberArguments(true, "https://dav.example.test/a.kdbx", "user"); + check("recent projection: webdav source keeps url and username", + kind == "webdav" && url == "https://dav.example.test/a.kdbx" && user == "user"); + + (kind, url, user) = RecentDatabaseList.RememberArguments(false, "https://stale.example.test/x.kdbx", "user"); + check("recent projection: local source drops a stale webdav target", + kind == "local" && url is null && user is null); + + (kind, url, user) = RecentDatabaseList.RememberArguments(false, null, null); + check("recent projection: plain local path is remembered local", + kind == "local" && url is null && user is null); + + // webdav detection behind the select decision + check("recent projection: webdav entry with url opens through webdav", + RecentDatabaseList.IsWebDavEntry(webDav)); + check("recent projection: webdav entry without url opens local", + !RecentDatabaseList.IsWebDavEntry(webDavNoUrl)); + check("recent projection: local entry with a stray url still opens local", + !RecentDatabaseList.IsWebDavEntry(new RecentDatabaseEntry + { + Path = vaultA, Kind = "local", WebDavUrl = "https://dav.example.test/a.kdbx", + })); + check("recent projection: kind match is case-insensitive", + RecentDatabaseList.IsWebDavEntry(new RecentDatabaseEntry + { + Path = vaultA, Kind = "WebDAV", WebDavUrl = "https://dav.example.test/a.kdbx", + })); + + // accessibility text decisions + check("accessibility: blank announcement is skipped", + !AccessibilityText.ShouldAnnounce("") && !AccessibilityText.ShouldAnnounce(" ") && + !AccessibilityText.ShouldAnnounce(null)); + check("accessibility: real announcement is raised", + AccessibilityText.ShouldAnnounce("Database locked")); + check("accessibility: empty help text does not override", + !AccessibilityText.ShouldSetHelpText("") && !AccessibilityText.ShouldSetHelpText(" ") && + !AccessibilityText.ShouldSetHelpText(null)); + check("accessibility: real help text is set", + AccessibilityText.ShouldSetHelpText("Opens the selected entry")); + check("accessibility: automation id only set when present", + !AccessibilityText.ShouldSetAutomationId("") && + AccessibilityText.ShouldSetAutomationId("UnlockLanguageCombo")); + + // projection over the real store: newest-first plus the projection text + string storePath = Path.Combine(directory, "projection.json"); + var store = new RecentDatabaseStore(storePath); + store.Remember(Path.Combine(directory, "one.kdbx"), "local"); + store.Remember(Path.Combine(directory, "two.kdbx"), "webdav", + "https://dav.example.test/two.kdbx", "user"); + store.Remember(Path.Combine(directory, "one.kdbx"), "local"); + check("recent projection: store is newest-first after re-remember", + store.Entries.Count == 2 && store.Entries[0].Path == Path.Combine(directory, "one.kdbx"), + store.Entries.Count.ToString()); + check("recent projection: secondary text follows each entry's kind", + RecentDatabaseList.SecondaryText(store.Entries[0]).EndsWith("one.kdbx") && + RecentDatabaseList.SecondaryText(store.Entries[1]).StartsWith("WebDAV · ")); + check("recent projection: visibility over the live store", + RecentDatabaseList.SectionVisible(true, store.Entries.Count) && + !RecentDatabaseList.SectionVisible(false, store.Entries.Count)); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/RemoteCacheCleanerTests.cs b/tests/app-core/Keepassity.Core.Tests/RemoteCacheCleanerTests.cs new file mode 100644 index 0000000..c4f4040 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/RemoteCacheCleanerTests.cs @@ -0,0 +1,189 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Security.Cryptography; +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// The WebDAV cache may be pruned only for copies that can be downloaded again: +/// a clean copy whose baseline hash matches its file and which has not been +/// touched for the retention window. Dirty, unknown and listed copies stay. +/// +internal static class RemoteCacheCleanerTests +{ + private const string FixtureName = "test_db_kdbx4_with_password_aes.kdbx"; + + public static void Run(TestCheck check, string dataDirectory) + { + PrunesOldCleanCopy(check, dataDirectory); + KeepsDirtyCopy(check, dataDirectory); + KeepsRecentCleanCopy(check, dataDirectory); + KeepsUnknownProvenance(check, dataDirectory); + KeepsListedCopy(check, dataDirectory); + KeepsHashMismatch(check, dataDirectory); + CleansOrphanLeftovers(check, dataDirectory); + PrunedCopyLeavesRecentList(check, dataDirectory); + } + + private static void PrunesOldCleanCopy(TestCheck check, string dataDirectory) + { + using var scope = new IsolatedRoot(dataDirectory, "prune-clean"); + (string working, string url, string user) = CreateCachedCopy( + scope.States, clean: true, old: true); + BackupEntry? backup = BackupService.CreateBackup(working, 5, "test"); + string? metadata = RemoteDatabaseStore.MetadataPathFor(working); + string statePath = scope.States.StatePathFor(url, user, working); + + RemoteCacheCleanupResult result = scope.NewCleaner().Prune(Array.Empty(), + TimeSpan.FromDays(90)); + check("remote cache: an old clean working copy is pruned", + result.RemovedWorkingCopies == 1 && !File.Exists(working), result.ToString()); + check("remote cache: pruning removes its backups, metadata and sync state", + backup is not null && !Directory.Exists(BackupService.BackupDirectory(working)) && + metadata is not null && !File.Exists(metadata) && !File.Exists(statePath)); + } + + private static void KeepsDirtyCopy(TestCheck check, string dataDirectory) + { + using var scope = new IsolatedRoot(dataDirectory, "keep-dirty"); + (string working, _, _) = CreateCachedCopy(scope.States, clean: false, old: true); + + RemoteCacheCleanupResult result = scope.NewCleaner().Prune(Array.Empty(), + TimeSpan.FromDays(90)); + check("remote cache: a copy with unsynced edits is never pruned", + File.Exists(working) && result.KeptDirty == 1, result.ToString()); + } + + private static void KeepsRecentCleanCopy(TestCheck check, string dataDirectory) + { + using var scope = new IsolatedRoot(dataDirectory, "keep-recent"); + (string working, _, _) = CreateCachedCopy(scope.States, clean: true, old: false); + + RemoteCacheCleanupResult result = scope.NewCleaner().Prune(Array.Empty(), + TimeSpan.FromDays(90)); + check("remote cache: a recently used clean copy is kept", + File.Exists(working) && result.KeptRecent == 1, result.ToString()); + } + + private static void KeepsUnknownProvenance(TestCheck check, string dataDirectory) + { + using var scope = new IsolatedRoot(dataDirectory, "keep-unknown"); + Directory.CreateDirectory(RemoteDatabaseStore.Root); + string working = Path.Combine(RemoteDatabaseStore.Root, + Guid.NewGuid().ToString("N") + ".kdbx"); + File.WriteAllBytes(working, File.ReadAllBytes(TestEnvironment.Fixture(FixtureName))); + File.SetLastWriteTimeUtc(working, DateTime.UtcNow.AddDays(-200)); + + RemoteCacheCleanupResult result = scope.NewCleaner().Prune(Array.Empty(), + TimeSpan.FromDays(90)); + check("remote cache: a copy without source metadata is kept", + File.Exists(working) && result.KeptUnknown == 1, result.ToString()); + } + + private static void KeepsListedCopy(TestCheck check, string dataDirectory) + { + using var scope = new IsolatedRoot(dataDirectory, "keep-listed"); + (string working, _, _) = CreateCachedCopy(scope.States, clean: true, old: true); + + RemoteCacheCleanupResult result = scope.NewCleaner() + .Prune(new[] { working }, TimeSpan.FromDays(90)); + check("remote cache: the current target is kept even when old and clean", + File.Exists(working) && result.RemovedWorkingCopies == 0, result.ToString()); + } + + private static void KeepsHashMismatch(TestCheck check, string dataDirectory) + { + using var scope = new IsolatedRoot(dataDirectory, "keep-mismatch"); + (string working, _, _) = CreateCachedCopy(scope.States, clean: true, old: true); + // The recorded baseline no longer matches the file: it may contain local + // edits whose sidecar was lost, so it is treated as dirty. + File.WriteAllBytes(working, new byte[] { 9, 9, 9 }); + File.SetLastWriteTimeUtc(working, DateTime.UtcNow.AddDays(-200)); + + RemoteCacheCleanupResult result = scope.NewCleaner().Prune(Array.Empty(), + TimeSpan.FromDays(90)); + check("remote cache: a copy whose baseline hash does not match is kept", + File.Exists(working) && result.KeptDirty == 1, result.ToString()); + } + + private static void CleansOrphanLeftovers(TestCheck check, string dataDirectory) + { + using var scope = new IsolatedRoot(dataDirectory, "orphans"); + (string working, _, _) = CreateCachedCopy(scope.States, clean: true, old: true); + _ = BackupService.CreateBackup(working, 5, "test"); + string? metadata = RemoteDatabaseStore.MetadataPathFor(working); + File.Delete(working); + + RemoteCacheCleanupResult result = scope.NewCleaner().Prune(Array.Empty(), + TimeSpan.FromDays(90)); + check("remote cache: leftovers of a vanished working copy are removed", + result.RemovedOrphans >= 1 && + !Directory.Exists(BackupService.BackupDirectory(working)) && + metadata is not null && !File.Exists(metadata), result.ToString()); + } + + private static void PrunedCopyLeavesRecentList(TestCheck check, string dataDirectory) + { + using var scope = new IsolatedRoot(dataDirectory, "recent-prune"); + (string working, string url, string user) = CreateCachedCopy( + scope.States, clean: true, old: true); + var recents = new RecentDatabaseStore(); + recents.Remember(working, "webdav", url, user); + + RemoteCacheCleanupResult result = scope.NewCleaner(recents) + .Prune(Array.Empty(), TimeSpan.FromDays(90)); + check("remote cache: pruning also forgets the deleted working copy in recents", + result.RemovedWorkingCopies == 1 && recents.Entries.Count == 0 && + !File.Exists(working), recents.Entries.Count.ToString()); + } + + private static (string Working, string Url, string User) CreateCachedCopy( + SyncStateStore states, bool clean, bool old) + { + string url = "https://example.test/" + Guid.NewGuid().ToString("N") + ".kdbx"; + const string user = "user"; + string working = RemoteDatabaseStore.PathFor(url, user); + byte[] bytes = File.ReadAllBytes(TestEnvironment.Fixture(FixtureName)); + File.WriteAllBytes(working, bytes); + RemoteDatabaseStore.WriteMetadata(url, user); + SyncState state = states.Load(url, user, working); + state.Etag = "\"etag\""; + state.Sha256 = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(); + state.Size = bytes.Length; + state.LocalDirty = !clean; + state.LastSyncUnix = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + states.Save(url, user, working, state); + if (old) + { + File.SetLastWriteTimeUtc(working, DateTime.UtcNow.AddDays(-200)); + } + return (working, url, user); + } + + /// + /// ApplicationPaths.Root is process-wide, so each check points the data root + /// at a fresh directory and restores the previous one afterwards. + /// + private sealed class IsolatedRoot : IDisposable + { + private readonly string? _previous; + + public IsolatedRoot(string dataDirectory, string name) + { + _previous = Environment.GetEnvironmentVariable("KEEPASSITY_DATA_DIR"); + string root = Path.Combine(dataDirectory, + "remote-cache-" + name + "-" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(root); + Environment.SetEnvironmentVariable("KEEPASSITY_DATA_DIR", root); + States = new SyncStateStore(); + } + + public SyncStateStore States { get; } + + public RemoteCacheCleaner NewCleaner(RecentDatabaseStore? recents = null) + => new(States, () => DateTimeOffset.UtcNow, recents); + + public void Dispose() + => Environment.SetEnvironmentVariable("KEEPASSITY_DATA_DIR", _previous); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/RemoteVaultOpenIntegrationTests.cs b/tests/app-core/Keepassity.Core.Tests/RemoteVaultOpenIntegrationTests.cs new file mode 100644 index 0000000..7346867 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/RemoteVaultOpenIntegrationTests.cs @@ -0,0 +1,198 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// End-to-end check of the WebDAV open path with the real native core and a real +// (loopback) WebDAV server: the downloaded bytes must decrypt before they are +// allowed to replace the working copy. +using System.Runtime.InteropServices; +using System.Text; +using System.Text.Json; +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +internal static class RemoteVaultOpenIntegrationTests +{ + public static void Run(TestCheck check, string dataDirectory) + { + if (TestEnvironment.FindFfiLibrary() is null) + { + Console.WriteLine("SKIP remote open integration (native FFI not built)"); + return; + } + // Touch the resolver owner first so the assembly-wide DllImport resolver + // is registered before this file's own P/Invokes are used. + _ = CoreValidation.LibraryPath; + + string name = "remote-integration-" + Guid.NewGuid().ToString("N")[..8]; + string folder = Path.Combine(dataDirectory, name); + Directory.CreateDirectory(folder); + byte[] fixture = File.ReadAllBytes(TestEnvironment.Fixture("test_db_few_rounds.kdbx")); + using var server = new WebDavMockServer(); + const string target = "/dav/open-integration.kdbx"; + server.PutResource(target, fixture, "\"e1\"", DateTimeOffset.UtcNow); + string url = $"http://127.0.0.1:{server.Port}{target}"; + var states = new SyncStateStore(Path.Combine(folder, "state")); + var opener = new RemoteVaultOpener(states); + using var remote = new WebDavClient(url, "user", "pass"); + PendingRemoteDatabase pending = opener.DownloadAsync(remote, url, "user") + .GetAwaiter().GetResult(); + check("remote open downloads the fixture", pending.Bytes.SequenceEqual(fixture)); + + // Put a distinguishable previous working copy in place so "untouched" + // means untouched, not "absent". + string workingCopy = pending.WorkingCopyPath; + byte[] oldBytes = { 1, 2, 3 }; + Directory.CreateDirectory(Path.GetDirectoryName(workingCopy)!); + File.WriteAllBytes(workingCopy, oldBytes); + + using var core = new RealCoreClient(); + bool rejected = false; + try + { + opener.OpenAsync(pending, core, "not-the-password").GetAwaiter().GetResult(); + } + catch (CoreException ex) + { + rejected = ex.Code == "BadPassword"; + } + check("remote open rejects a wrong master password", + rejected && !core.IsOpen, + rejected ? "BadPassword" : "no BadPassword"); + check("remote open leaves the working copy untouched after a wrong password", + File.ReadAllBytes(workingCopy).SequenceEqual(oldBytes)); + + opener.OpenAsync(pending, core, "demopass").GetAwaiter().GetResult(); + SyncState state = states.Load(url, "user", workingCopy); + check("remote open promotes bytes that really decrypt with the password", + core.IsOpen && File.ReadAllBytes(workingCopy).SequenceEqual(fixture)); + check("remote open records the real synced baseline", + !state.LocalDirty && state.Etag == "\"e1\"" && + state.Sha256 == Sha(fixture) && state.Size == fixture.Length, + state.Sha256 ?? "(none)"); + check("remote open backs up the previous working copy", + BackupService.ListBackups(workingCopy).Count == 1 && + File.ReadAllBytes(BackupService.ListBackups(workingCopy)[0].Path) + .SequenceEqual(oldBytes)); + } + + private static string Sha(byte[] bytes) + => Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(bytes)) + .ToLowerInvariant(); + + /// Minimal live core handle for the integration check. + private sealed class RealCoreClient : ICoreClient + { + public Task GetDatabaseInfoAsync() + => Task.FromResult(new DatabaseInfoDto()); + + public Task SetKdfAsync(string preset) + => Task.FromResult(new DatabaseInfoDto()); + + private const string Library = "keepassity_ffi"; + + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNameCaseInsensitive = true, + }; + + private IntPtr _handle; + + [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] + private static extern uint kp_api_version(); + + [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] + private static extern IntPtr kp_open(byte[] kdbx, UIntPtr len, byte[] optsJson); + + [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] + private static extern int kp_lock(IntPtr handle); + + [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] + private static extern int kp_close(IntPtr handle); + + [DllImport(Library, CallingConvention = CallingConvention.Cdecl)] + private static extern IntPtr kp_last_error_json(); + + public bool IsOpen => _handle != IntPtr.Zero; + + public string? DatabasePath { get; private set; } + + public Task OpenAsync(string path, string password) + { + byte[] bytes = File.ReadAllBytes(path); + return OpenBytesAsync(bytes, password, path); + } + + public Task OpenBytesAsync(byte[] kdbx, string password, string? databasePath = null) + { + if (kp_api_version() != 1) + { + throw new CoreException("VersionMismatch", "unsupported FFI version"); + } + if (_handle != IntPtr.Zero) + { + _ = kp_close(_handle); + _handle = IntPtr.Zero; + } + byte[] options = Encoding.UTF8.GetBytes( + JsonSerializer.Serialize(new { password }) + "\0"); + IntPtr handle = kp_open(kdbx, (UIntPtr)kdbx.LongLength, options); + if (handle == IntPtr.Zero) + { + throw ParseError("open database"); + } + _handle = handle; + DatabasePath = databasePath; + return Task.CompletedTask; + } + + public Task LockAsync() + { + if (_handle != IntPtr.Zero && kp_lock(_handle) != 0) + { + throw ParseError("lock database"); + } + return Task.CompletedTask; + } + + public Task SaveBytesAsync() => throw new NotSupportedException(); + + public Task SaveAsync(string path, int backupRetention = 20, + Func? databaseChanged = null) + => throw new NotSupportedException(); + + public Task VerifyAsync(byte[] bytes, string password) + => throw new NotSupportedException(); + + public Task SyncDecideAsync(string remoteMetaJson, bool localDirty) + => throw new NotSupportedException(); + + public Task SyncCommitAsync(string? etag, string? sha256) + => throw new NotSupportedException(); + + public void Dispose() + { + if (_handle != IntPtr.Zero) + { + _ = kp_close(_handle); + _handle = IntPtr.Zero; + } + } + + private static CoreException ParseError(string operation) + { + try + { + IntPtr pointer = kp_last_error_json(); + string json = pointer == IntPtr.Zero + ? "{}" + : Marshal.PtrToStringUTF8(pointer) ?? "{}"; + ErrorDto? error = JsonSerializer.Deserialize(json, JsonOptions); + return new CoreException(error?.Code ?? "Internal", + error?.Message ?? $"{operation} failed."); + } + catch (JsonException) + { + return new CoreException("Internal", $"{operation} failed."); + } + } + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/RemoteVaultOpenerTests.cs b/tests/app-core/Keepassity.Core.Tests/RemoteVaultOpenerTests.cs new file mode 100644 index 0000000..6bcd108 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/RemoteVaultOpenerTests.cs @@ -0,0 +1,312 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// The WebDAV open path must never let unverified bytes touch the working copy. +/// These checks pin the rule down: download only holds memory, the master +/// password opens the bytes first, and only then is the working copy written +/// durably with a backup and a clean sync baseline. +/// +internal static class RemoteVaultOpenerTests +{ + private const string User = "user"; + private const string Password = "master-password"; + + private static string UrlFor(string name) => $"https://example.test/open-{name}.kdbx"; + public static void Run(TestCheck check, string dataDirectory) + { + DownloadHoldsBytesInMemory(check, dataDirectory); + MissingRemoteIsReported(check, dataDirectory); + OpenPromotesOnlyAfterDecrypting(check, dataDirectory); + WrongPasswordLeavesDiskUntouched(check, dataDirectory); + WriteFailureLocksTheCore(check, dataDirectory); + } + + private static void DownloadHoldsBytesInMemory(TestCheck check, string dataDirectory) + { + (string folder, SyncStateStore states) = NewEnvironment(dataDirectory, "download"); + string url = UrlFor("download"); + var remote = new FakeRemote { Bytes = Bytes(1, 2, 3, 4) }; + var opener = new RemoteVaultOpener(states); + + PendingRemoteDatabase pending = opener.DownloadAsync(remote, url, User, 5) + .GetAwaiter().GetResult(); + + check("download keeps the remote bytes pending", + pending.Bytes.SequenceEqual(Bytes(1, 2, 3, 4)) && + pending.Metadata.ETag == "\"e1\"" && + pending.Url == url && pending.Username == User && + pending.BackupRetention == 5); + check("download does not write the working copy", + pending.WorkingCopyPath == RemoteDatabaseStore.PathFor(url, User) && + !File.Exists(pending.WorkingCopyPath)); + check("download does not write a sync baseline", + states.Load(url, User, pending.WorkingCopyPath).Sha256 is null); + check("download leaves no temporary file behind", + Directory.GetFiles(folder).Length == 0 && + Directory.GetDirectories(folder).Length == 1, + string.Join("; ", Directory.GetFileSystemEntries(folder))); + } + + private static void MissingRemoteIsReported(TestCheck check, string dataDirectory) + { + (_, SyncStateStore states) = NewEnvironment(dataDirectory, "missing"); + string url = UrlFor("missing"); + var remote = new FakeRemote { Missing = true }; + var opener = new RemoteVaultOpener(states); + + WebDavException? error = null; + try + { + opener.DownloadAsync(remote, url, User).GetAwaiter().GetResult(); + } + catch (WebDavException ex) + { + error = ex; + } + + check("a missing remote file is reported as not found", + error is not null && error.StatusCode == 404, + error?.StatusCode.ToString() ?? "no exception"); + } + + private static void OpenPromotesOnlyAfterDecrypting(TestCheck check, string dataDirectory) + { + (_, SyncStateStore states) = NewEnvironment(dataDirectory, "promote"); + string url = UrlFor("promote"); + byte[] oldBytes = Bytes(9, 9, 9); + byte[] remoteBytes = Bytes(5, 6, 7, 8); + string workingCopy = RemoteDatabaseStore.PathFor(url, User); + Directory.CreateDirectory(Path.GetDirectoryName(workingCopy)!); + File.WriteAllBytes(workingCopy, oldBytes); + states.Save(url, User, workingCopy, new SyncState + { + Etag = "\"old\"", + Sha256 = new string('a', 64), + LocalDirty = true, + }); + var remote = new FakeRemote { Bytes = remoteBytes }; + var core = new FakeCore(); + // Capture what is on disk at the moment the bytes are opened: the open + // must come first, the working-copy write second. + byte[]? onDiskDuringOpen = null; + core.OnOpenBytes = (_, _, _) => + { + onDiskDuringOpen = File.ReadAllBytes(workingCopy); + return Task.CompletedTask; + }; + PendingRemoteDatabase pending = new RemoteVaultOpener(states) + .DownloadAsync(remote, url, User).GetAwaiter().GetResult(); + var opener = new RemoteVaultOpener(states); + + opener.OpenAsync(pending, core, Password).GetAwaiter().GetResult(); + + check("the downloaded bytes are opened before the working copy changes", + onDiskDuringOpen is not null && onDiskDuringOpen.SequenceEqual(oldBytes), + onDiskDuringOpen is null + ? "open not called" + : Convert.ToHexString(onDiskDuringOpen)); + check("promotion passes the bytes, password and path to the core", + core.OpenBytesCalls == 1 && + core.OpenedBytes?.SequenceEqual(remoteBytes) == true && + core.OpenedPassword == Password && + core.OpenedPath == workingCopy); + check("promotion replaces the working copy with the verified bytes", + File.ReadAllBytes(workingCopy).SequenceEqual(remoteBytes)); + SyncState state = states.Load(url, User, workingCopy); + check("promotion records a clean synced baseline", + !state.LocalDirty && + state.Etag == "\"e1\"" && + state.Sha256 == Sha(remoteBytes) && + state.Size == remoteBytes.Length && + state.RemoteModifiedUnix == 1234); + List backups = BackupService.ListBackups(workingCopy); + check("promotion backs up the previous working copy", + backups.Count == 1 && File.ReadAllBytes(backups[0].Path).SequenceEqual(oldBytes), + backups.Count.ToString()); + check("promotion leaves no temporary file behind", + Directory.GetFiles(Path.GetDirectoryName(workingCopy)!, + "*keepassity-tmp*").Length == 0); + } + + private static void WrongPasswordLeavesDiskUntouched(TestCheck check, string dataDirectory) + { + (_, SyncStateStore states) = NewEnvironment(dataDirectory, "wrong-password"); + string url = UrlFor("wrong-password"); + byte[] oldBytes = Bytes(4, 4, 4); + string workingCopy = RemoteDatabaseStore.PathFor(url, User); + Directory.CreateDirectory(Path.GetDirectoryName(workingCopy)!); + File.WriteAllBytes(workingCopy, oldBytes); + states.Save(url, User, workingCopy, new SyncState { LocalDirty = true }); + var remote = new FakeRemote { Bytes = Bytes(1, 2) }; + var core = new FakeCore + { + OnOpenBytes = (_, _, _) => Task.FromException( + new CoreException("BadPassword", "incorrect master password")), + }; + PendingRemoteDatabase pending = new RemoteVaultOpener(states) + .DownloadAsync(remote, url, User).GetAwaiter().GetResult(); + + bool threw = false; + try + { + new RemoteVaultOpener(states).OpenAsync(pending, core, "wrong") + .GetAwaiter().GetResult(); + } + catch (CoreException) + { + threw = true; + } + + check("a wrong password fails the open", threw); + check("a failed open leaves the working copy untouched", + File.ReadAllBytes(workingCopy).SequenceEqual(oldBytes)); + check("a failed open leaves the previous baseline dirty", + states.Load(url, User, workingCopy).LocalDirty); + check("a failed open creates no backup and locks nothing new", + BackupService.ListBackups(workingCopy).Count == 0 && core.LockCalls == 0); + } + + private static void WriteFailureLocksTheCore(TestCheck check, string dataDirectory) + { + (string folder, SyncStateStore states) = NewEnvironment(dataDirectory, "write-failure"); + // A file where the working copy's parent directory should be makes the + // durable write fail after the bytes were opened. + string blockedParent = Path.Combine(folder, "blocked"); + File.WriteAllText(blockedParent, "not a directory"); + string workingCopy = Path.Combine(blockedParent, "vault.kdbx"); + PendingRemoteDatabase pending = new() + { + Url = UrlFor("write-failure"), + Username = User, + WorkingCopyPath = workingCopy, + Metadata = new WebDavFileInfo { ETag = "\"e1\"", Size = 2, ModifiedUnix = 1 }, + Bytes = Bytes(1, 2), + }; + var core = new FakeCore(); + + bool threw = false; + try + { + new RemoteVaultOpener(states).OpenAsync(pending, core, Password) + .GetAwaiter().GetResult(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + threw = true; + } + + check("a failed promotion write is reported", threw); + check("a failed promotion write locks the opened core again", + core.OpenBytesCalls == 1 && core.LockCalls == 1, + $"open={core.OpenBytesCalls} lock={core.LockCalls}"); + check("a failed promotion write leaves no baseline", + states.Load(UrlFor("write-failure"), User, workingCopy).Sha256 is null); + } + + private static (string Folder, SyncStateStore States) NewEnvironment( + string dataDirectory, string name) + { + string folder = Path.Combine(dataDirectory, + "remote-open-" + name + "-" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(folder); + return (folder, new SyncStateStore(Path.Combine(folder, "state"))); + } + + private static byte[] Bytes(params byte[] values) => values; + + private static string Sha(byte[] bytes) + => Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(bytes)) + .ToLowerInvariant(); + + private sealed class FakeRemote : ISyncRemote + { + public WebDavFileInfo? Metadata { get; set; } = new() + { + ETag = "\"e1\"", + Size = 4, + ModifiedUnix = 1234, + }; + + public byte[] Bytes { get; set; } = new byte[] { 1, 2, 3, 4 }; + + public bool Missing { get; set; } + + public Task GetMetadataAsync( + CancellationToken cancellationToken = default) + => Task.FromResult(Missing ? null : Metadata); + + public Task DownloadAsync(CancellationToken cancellationToken = default) + => Missing + ? throw new WebDavException("missing", 404) + : Task.FromResult(Bytes); + + public Task UploadAsync(byte[] bytes, string? ifMatch, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + } + + private sealed class FakeCore : ICoreClient + { + public Task GetDatabaseInfoAsync() + => Task.FromResult(new DatabaseInfoDto()); + + public Task SetKdfAsync(string preset) + => Task.FromResult(new DatabaseInfoDto()); + + public Func? OnOpenBytes { get; set; } + + public int OpenBytesCalls { get; private set; } + + public byte[]? OpenedBytes { get; private set; } + + public string? OpenedPassword { get; private set; } + + public string? OpenedPath { get; private set; } + + public int LockCalls { get; private set; } + + public bool IsOpen => false; + + public string? DatabasePath { get; private set; } + + public Task OpenAsync(string path, string password) + => throw new NotSupportedException(); + + public Task OpenBytesAsync(byte[] kdbx, string password, string? databasePath = null) + { + OpenBytesCalls++; + OpenedBytes = kdbx; + OpenedPassword = password; + OpenedPath = databasePath; + DatabasePath = databasePath; + return OnOpenBytes?.Invoke(kdbx, password, databasePath) ?? Task.CompletedTask; + } + + public Task LockAsync() + { + LockCalls++; + return Task.CompletedTask; + } + + public Task SaveBytesAsync() => throw new NotSupportedException(); + + public Task SaveAsync(string path, int backupRetention = 20, + Func? databaseChanged = null) + => throw new NotSupportedException(); + + public Task VerifyAsync(byte[] bytes, string password) => throw new NotSupportedException(); + + public Task SyncDecideAsync(string remoteMetaJson, bool localDirty) + => throw new NotSupportedException(); + + public Task SyncCommitAsync(string? etag, string? sha256) + => throw new NotSupportedException(); + + public void Dispose() + { + } + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/RunStateStoreTests.cs b/tests/app-core/Keepassity.Core.Tests/RunStateStoreTests.cs new file mode 100644 index 0000000..c53114e --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/RunStateStoreTests.cs @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// The run marker separates a clean close from a crash/power loss, so the next +/// launch can point the user at the backups. Headless checks inject the process +/// probe instead of querying the real process table. +/// +internal static class RunStateStoreTests +{ + public static void Run(TestCheck check, string rootDirectory) + { + CleanAndCrashedRuns(check, rootDirectory); + LiveProcessIsNotACrash(check, rootDirectory); + MalformedMarkerCountsAsACrash(check, rootDirectory); + MarkIsAtomic(check, rootDirectory); + } + + private static void CleanAndCrashedRuns(TestCheck check, string rootDirectory) + { + string directory = Path.Combine(rootDirectory, + "run-state-" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(directory); + string path = Path.Combine(directory, "run.json"); + var store = new RunStateStore(path, pid => pid == Environment.ProcessId); + + check("run state: a fresh data folder has no previous run", + store.DetectPreviousCrash() is null); + + DateTimeOffset started = DateTimeOffset.UtcNow.AddMinutes(-5); + store.MarkRunning(started); + check("run state: marking writes the marker", File.Exists(path)); + check("run state: a marker for this live process is not a crash", + store.DetectPreviousCrash() is null); + + store.Clear(); + check("run state: a clean close removes the marker", !File.Exists(path)); + check("run state: a clean close leaves no crash report", + store.DetectPreviousCrash() is null); + + // A dead process id: the marker survived a crash. + File.WriteAllText(path, + "{\"Pid\":999999,\"StartedUnix\":" + started.ToUnixTimeSeconds() + "}"); + PreviousRun? crashed = store.DetectPreviousCrash(); + check("run state: a marker from a dead process is a crash report", + crashed is not null && crashed.ProcessId == 999999 && + Math.Abs((crashed.StartedAt - started).TotalSeconds) < 1, + crashed?.ToString() ?? "(none)"); + store.Clear(); + } + + private static void LiveProcessIsNotACrash(TestCheck check, string rootDirectory) + { + string path = Path.Combine(rootDirectory, + "run-live-" + Guid.NewGuid().ToString("N")[..8] + ".json"); + File.WriteAllText(path, "{\"Pid\":1234,\"StartedUnix\":1700000000}"); + var store = new RunStateStore(path, pid => pid == 1234); + check("run state: a marker held by a live process is ignored", + store.DetectPreviousCrash() is null); + store.Clear(); + } + + private static void MalformedMarkerCountsAsACrash(TestCheck check, string rootDirectory) + { + string path = Path.Combine(rootDirectory, + "run-corrupt-" + Guid.NewGuid().ToString("N")[..8] + ".json"); + File.WriteAllText(path, "{not valid json"); + var store = new RunStateStore(path, _ => false); + PreviousRun? crashed = store.DetectPreviousCrash(); + check("run state: a malformed marker is reported as a crash", + crashed is not null && crashed.ProcessId == 0, crashed?.ToString() ?? "(none)"); + store.Clear(); + check("run state: clearing a malformed marker works", !File.Exists(path)); + } + + private static void MarkIsAtomic(TestCheck check, string rootDirectory) + { + string directory = Path.Combine(rootDirectory, + "run-atomic-" + Guid.NewGuid().ToString("N")[..8]); + string path = Path.Combine(directory, "nested", "run.json"); + var store = new RunStateStore(path, _ => true); + store.MarkRunning(); + check("run state: marking creates the state folder and file", + File.Exists(path) && store.DetectPreviousCrash() is null); + check("run state: marking leaves no temporary file", + Directory.GetFiles(Path.GetDirectoryName(path)!, "*keepassity-tmp*") + .Length == 0); + store.Clear(); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/SettingsAndCredentialTests.cs b/tests/app-core/Keepassity.Core.Tests/SettingsAndCredentialTests.cs index 259812f..65e70ac 100644 --- a/tests/app-core/Keepassity.Core.Tests/SettingsAndCredentialTests.cs +++ b/tests/app-core/Keepassity.Core.Tests/SettingsAndCredentialTests.cs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later using System.Text; -using Keepassity.Mock; +using System.Text.Json; +using Keepassity.Core; namespace Keepassity.CoreTests; @@ -19,9 +20,43 @@ internal static class SettingsAndCredentialTests public static void Run(TestCheck check) { RunSettingsProof(check); + RunSettingsRecovery(check); RunCredentialLifecycle(check); } + private static void RunSettingsRecovery(TestCheck check) + { + string directory = Path.Combine(ApplicationPaths.Root, + "settings-recovery-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + + string corruptPath = Path.Combine(directory, "settings.json"); + File.WriteAllText(corruptPath, "{ this is not json"); + var corrupt = new AppSettingsStore(corruptPath); + check("settings: corrupt file falls back to defaults", + corrupt.Current.Theme == "Dark" && !corrupt.IsReadOnly, corrupt.Current.Theme); + check("settings: corrupt file is preserved for diagnosis", + Directory.GetFiles(directory, "settings.json.corrupt-*").Length == 1); + + string newerPath = Path.Combine(directory, "newer", "settings.json"); + Directory.CreateDirectory(Path.GetDirectoryName(newerPath)!); + File.WriteAllText(newerPath, + "{\"SchemaVersion\":2,\"Theme\":\"Light\",\"FutureField\":\"keep-me\"}"); + var newer = new AppSettingsStore(newerPath); + check("settings: newer schema is readable", newer.Current.Theme == "Light", + newer.Current.Theme); + check("settings: newer schema is read-only", newer.IsReadOnly); + newer.Current.Theme = "Dark"; + newer.Save(); + using JsonDocument after = JsonDocument.Parse(File.ReadAllText(newerPath)); + JsonElement root = after.RootElement; + check("settings: saving a newer schema does not downgrade it", + root.GetProperty("SchemaVersion").GetInt32() == 2 && + root.GetProperty("Theme").GetString() == "Light" && + root.GetProperty("FutureField").GetString() == "keep-me", + root.ToString()); + } + private static void RunSettingsProof(TestCheck check) { var settings = new AppSettingsStore(); @@ -31,7 +66,7 @@ private static void RunSettingsProof(TestCheck check) settings.Current.LastWebDavUsername = WebDavUser; settings.Save(); - string settingsPath = Path.Combine(AppDataPaths.Root, "settings.json"); + string settingsPath = Path.Combine(ApplicationPaths.Root, "settings.json"); check("settings: file written", File.Exists(settingsPath), settingsPath); string json = File.ReadAllText(settingsPath); check("settings: WebDAV password is not present", @@ -74,10 +109,31 @@ private static void RunCredentialLifecycle(TestCheck check) check("credential: keyed by username", !credentials.HasPassword(WebDavUrl, "other-user")); + // A blob from another user/machine or a truncated file must not throw + // into the settings/sync UI; it is preserved and treated as absent. + string corruptUrl = "https://dav.example.test/corrupt.kdbx"; + string corruptCredentialDir = Path.Combine(ApplicationPaths.Root, "credentials"); + var before = Directory.GetFiles(corruptCredentialDir, "*.bin").ToHashSet( + StringComparer.OrdinalIgnoreCase); + credentials.SavePassword(corruptUrl, WebDavUser, "corrupt-me"); + string? blob = Directory.GetFiles(corruptCredentialDir, "*.bin") + .FirstOrDefault(path => !before.Contains(path)); + check("credential: corrupt-test blob created", blob is not null); + if (blob is not null) + { + File.WriteAllBytes(blob, new byte[] { 1, 2, 3 }); + string? corruptLoaded = credentials.LoadPassword(corruptUrl, WebDavUser); + check("credential: corrupt blob loads as absent", corruptLoaded is null); + check("credential: corrupt blob is preserved", + Directory.GetFiles(corruptCredentialDir, "*.corrupt-*").Length > 0); + check("credential: corrupt blob no longer advertised", + !credentials.HasPassword(corruptUrl, WebDavUser)); + } + // The on-disk credential blob must be DPAPI-protected, not plaintext. - string credentialDirectory = Path.Combine(AppDataPaths.Root, "credentials"); + string credentialDirectory = Path.Combine(ApplicationPaths.Root, "credentials"); string[] blobs = Directory.Exists(credentialDirectory) - ? Directory.GetFiles(credentialDirectory, "*.bin") + ? Directory.GetFiles(corruptCredentialDir, "*.bin") : Array.Empty(); check("credential: protected blob written", blobs.Length >= 1, blobs.Length.ToString()); @@ -88,7 +144,7 @@ private static void RunCredentialLifecycle(TestCheck check) // Nothing else under the data root may contain the WebDAV password: // the settings/config proof is a real grep, not just a field check. byte[] passwordBytes = Encoding.UTF8.GetBytes(WebDavPassword); - string[] configFiles = Directory.GetFiles(AppDataPaths.Root, "*", + string[] configFiles = Directory.GetFiles(ApplicationPaths.Root, "*", SearchOption.AllDirectories) .Where(path => !path.StartsWith(credentialDirectory + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) diff --git a/tests/app-core/Keepassity.Core.Tests/SettingsViewModelTests.cs b/tests/app-core/Keepassity.Core.Tests/SettingsViewModelTests.cs new file mode 100644 index 0000000..5a09960 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/SettingsViewModelTests.cs @@ -0,0 +1,186 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Headless behaviour checks for the Settings view model. +using Keepassity.Core; +using Keepassity.ViewModels; + +namespace Keepassity.CoreTests; + +internal static class SettingsViewModelTests +{ + public static void Run(TestCheck check) + { + void Check(string name, bool ok, string detail = "") => check(name, ok, detail); + + var settings = new AppSettings + { + Theme = "Dark", + Language = "zh-CN", + ClearClipboardAfter30Seconds = true, + AutoLockEnabled = true, + StartMinimized = false, + AutoLockMinutes = 15, + BackupRetention = 7, + SyncOnSave = true, + WebDavUrl = "https://dav.example.test/vault.kdbx", + WebDavUsername = "alice", + }; + var host = new FakeHost(); + var vm = new SettingsViewModel(settings, host, FakeText.Instance); + + Check("settings maps the stored appearance", + vm.ThemeIndex == 2, vm.ThemeIndex.ToString()); + Check("settings maps the stored language", + vm.SelectedLanguage == "zh-CN", vm.SelectedLanguage); + Check("settings maps the stored toggles", + vm.ClearClipboardAfter30Seconds && vm.AutoLockEnabled && + !vm.StartMinimized && vm.SyncOnSave); + Check("settings maps numeric values", + vm.AutoLockMinutes == 15 && vm.BackupRetention == 7); + Check("settings offers the host languages", + vm.Languages.Count == host.Languages.Count); + + vm.ThemeIndex = 1; + Check("theme change applies and saves immediately", + settings.Theme == "Light" && host.Themes.Contains("Light") && + host.Saves == 1); + vm.ThemeIndex = 1; + Check("unchanged theme does not save again", host.Saves == 1); + + vm.AutoLockMinutes = 999; + Check("auto-lock minutes are clamped", + vm.AutoLockMinutes == 240 && settings.AutoLockMinutes == 240); + vm.BackupRetention = 0; + Check("backup retention is clamped", + vm.BackupRetention == 1 && settings.BackupRetention == 1); + vm.StartMinimized = true; + Check("toggle changes are saved", + settings.StartMinimized && host.Saves >= 4); + + int applies = host.LanguageApplies; + vm.SelectedLanguage = "en"; + Check("language change is applied through the host", + host.LanguageApplies == applies + 1 && host.LastLanguage == "en"); + + // The WebDAV source and the per-database switches moved to the database + // settings page (ADR-0034); this page only commits its own settings. + var result = vm.ApplyAsync().GetAwaiter().GetResult(); + Check("applying saves the application settings", result.Ok && host.Saves >= 5); + Check("applying does not request a sync", !result.SyncNow); + + host.SaveError = new IOException("disk full"); + var saveFailed = vm.ApplyAsync().GetAwaiter().GetResult(); + Check("settings save failure is reported", + !saveFailed.Ok && saveFailed.Error is not null); + host.SaveError = null; + + vm.ExportDiagnosticsAsync().GetAwaiter().GetResult(); + Check("diagnostics success is reported", + host.Toasts.Contains("Diagnostics exported: /tmp/diagnostics.zip")); + host.ExportError = new IOException("disk full"); + vm.ExportDiagnosticsAsync().GetAwaiter().GetResult(); + Check("diagnostics failure is reported", + host.Toasts.Any(toast => toast.Contains("Diagnostics export failed", + StringComparison.Ordinal))); + } + + private static string Key(string url, string user) => url + "\n" + user; + + private sealed class FakeText : IAppText + { + public static readonly FakeText Instance = new(); + + public string T(string english) => english; + + public string T(string format, params object?[] arguments) + => arguments.Length == 0 ? format : string.Format(format, arguments); + + public string TLong(string key, string english) => english; + } + + private sealed class FakeHost : ISettingsHost + { + public bool IsWebDavSource { get; set; } + + public string AppVersion { get; set; } = "1.2.3"; + + public IReadOnlyList Languages { get; } = new List + { + new LanguageOption("system", "System"), + new LanguageOption("en", "English"), + new LanguageOption("zh-CN", "简体中文"), + }; + + public HashSet Stored { get; } = new(StringComparer.Ordinal); + + public List<(string Url, string User, string Password)> StoredPasswords { get; } = + new(); + + public List<(string Url, string User)> Deleted { get; } = new(); + + public List Themes { get; } = new(); + + public List Toasts { get; } = new(); + + public int Saves { get; private set; } + + public int LanguageApplies { get; private set; } + + public string? LastLanguage { get; private set; } + + public Exception? StoreError { get; set; } + + public Exception? SaveError { get; set; } + + public Exception? DeleteError { get; set; } + + public Exception? ExportError { get; set; } + + public void ApplyTheme(string theme) => Themes.Add(theme); + + public void ApplyLanguage(string setting) + { + LanguageApplies++; + LastLanguage = setting; + } + + public void SaveSettings() + { + if (SaveError is not null) + { + throw SaveError; + } + Saves++; + } + + public bool HasStoredPassword(string url, string username) => + Stored.Contains(url + "\n" + username); + + public bool DeleteStoredPassword(string url, string username) + { + if (DeleteError is not null) + { + throw DeleteError; + } + Deleted.Add((url, username)); + return Stored.Remove(url + "\n" + username); + } + + public void StorePassword(string url, string username, string password) + { + if (StoreError is not null) + { + throw StoreError; + } + StoredPasswords.Add((url, username, password)); + Stored.Add(url + "\n" + username); + } + + public Task ExportDiagnosticsAsync() + => ExportError is null + ? Task.FromResult("/tmp/diagnostics.zip") + : Task.FromException(ExportError); + + public void ShowToast(string message, SettingsToastSeverity severity) + => Toasts.Add(message); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/SyncCoordinatorTests.cs b/tests/app-core/Keepassity.Core.Tests/SyncCoordinatorTests.cs new file mode 100644 index 0000000..72d0ca8 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/SyncCoordinatorTests.cs @@ -0,0 +1,892 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Security.Cryptography; +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// Behaviour of the sync coordinator, which owns the data-safety rules of a sync +/// run: verify before replacing, write before upload, commit after acceptance, +/// retry/back-off, conflict copies and dirty-on-failure. The fakes replace the +/// network and the native core so every rule can be asserted headlessly. +/// +internal static class SyncCoordinatorTests +{ + private const string Url = "https://example.test/db.kdbx"; + private const string User = "user"; + private const string Password = "master-password"; + + public static void Run(TestCheck check, string dataDirectory) + { + FirstUpload(check, dataDirectory); + UpToDate(check, dataDirectory); + UpToDateNeedsBaseline(check, dataDirectory); + StaleCleanBaseline(check, dataDirectory); + Download(check, dataDirectory); + RejectedDownload(check, dataDirectory); + DownloadReplaceFailure(check, dataDirectory); + UploadBackoff(check, dataDirectory); + ExhaustedUploadMerges(check, dataDirectory); + ConflictChoices(check, dataDirectory); + ConflictCopiesAreReused(check, dataDirectory); + LocalEditDuringSync(check, dataDirectory); + LocalEditDuringUpload(check, dataDirectory); + UnreadableRemote(check, dataDirectory); + NothingQueued(check, dataDirectory); + } + + // ---------------------------------------------------------------- scenarios + + private static void FirstUpload(TestCheck check, string dataDirectory) + { + Harness harness = new(dataDirectory, "first-upload", Local("local")); + byte[] model = Local("model"); + harness.Core.ModelBytes = model; + harness.Remote.Missing = true; + + SyncReport report = harness.RunAsync().GetAwaiter().GetResult(); + SyncState state = harness.State; + + check("sync uploads the first version when the remote file is missing", + report.Outcome == SyncOutcome.Synced && harness.Remote.Uploaded.Count == 1 && + harness.Remote.Uploaded[0].SequenceEqual(model)); + check("first upload creates the file instead of overwriting", + harness.Remote.IfMatch.Count == 1 && harness.Remote.IfMatch[0] is null); + check("upload writes the database before uploading and commits last", + string.Join(",", harness.Events) == "write,upload,commit", + string.Join(",", harness.Events)); + check("upload records a clean baseline", + state.LocalDirty == false && state.Sha256 == Sha(model) && + state.Etag == harness.Remote.Metadata?.ETag && state.Size == model.Length); + check("upload reports the synced status", harness.LastStatus == "Synced", + harness.LastStatus); + } + + private static void UpToDate(TestCheck check, string dataDirectory) + { + Harness harness = new(dataDirectory, "up-to-date", Local("remote")); + harness.Remote.Bytes = Local("remote"); + harness.SaveCleanState(harness.Remote.Bytes, "\"old\""); + harness.Core.Decision = new SyncDecisionDto { Action = "up_to_date" }; + harness.Remote.Metadata = new WebDavFileInfo + { + ETag = "\"e2\"", + Size = harness.Remote.Bytes.Length, + ModifiedUnix = 700, + }; + + SyncReport report = harness.RunAsync().GetAwaiter().GetResult(); + SyncState state = harness.State; + + check("up-to-date sync writes nothing", + harness.Document.Writes.Count == 0 && harness.Remote.Uploaded.Count == 0 && + harness.Remote.Downloads == 0 && report.Notice == SyncNotice.None); + check("up-to-date sync adopts the remote baseline", + state.Etag == "\"e2\"" && !state.LocalDirty && state.RemoteModifiedUnix == 700); + check("up-to-date sync re-seeds and confirms the core baseline", + harness.Core.Commits.Count == 2 && + harness.Core.Commits[0].Sha == Sha(harness.Remote.Bytes) && + harness.Core.Commits[1].Etag == "\"e2\""); + check("up-to-date sync reports synced", harness.LastStatus == "Synced"); + check("a clean sidecar that matches the local file stays clean", + !harness.Core.LastLocalDirty); + + Harness degraded = new(dataDirectory, "degraded", Local("remote")); + degraded.Remote.Bytes = Local("remote"); + degraded.SaveCleanState(degraded.Remote.Bytes, "\"old\""); + degraded.Core.Decision = new SyncDecisionDto + { + Action = "up_to_date", + Degraded = true, + }; + SyncReport degradedReport = degraded.RunAsync().GetAwaiter().GetResult(); + check("a degraded up-to-date sync says so", + degradedReport.Degraded && degraded.LastStatus == "Synced (degraded)", + degraded.LastStatus); + } + + private static void UpToDateNeedsBaseline(TestCheck check, string dataDirectory) + { + Harness harness = new(dataDirectory, "needs-baseline", Local("local")); + harness.Remote.Bytes = Local("remote"); + harness.Core.Decision = new SyncDecisionDto { Action = "up_to_date" }; + + SyncReport report = harness.RunAsync().GetAwaiter().GetResult(); + SyncState state = harness.State; + + check("an up-to-date remote without a content hash is not trusted", + report.Outcome == SyncOutcome.NeedsBaseline && state.LocalDirty); + check("a missing baseline keeps the vault dirty and says why", + harness.LastStatus == "Sync needs baseline" && harness.Core.Commits.Count == 0, + harness.LastStatus); + } + + private static void StaleCleanBaseline(TestCheck check, string dataDirectory) + { + Harness harness = new(dataDirectory, "stale-clean", Local("saved-after-crash")); + harness.Remote.Bytes = Local("remote-stale"); + harness.SaveCleanState(harness.Remote.Bytes, "\"e1\""); + harness.Core.Decision = new SyncDecisionDto { Action = "upload" }; + + SyncReport report = harness.RunAsync().GetAwaiter().GetResult(); + + // A crash between the database write and the sidecar write leaves a clean + // sidecar pointing at the previous content. Treating that as synced would + // silently drop the upload, so the coordinator compares the file first. + check("a clean sidecar that disagrees with the local file is treated as dirty", + harness.Core.LastLocalDirty && report.Outcome == SyncOutcome.Synced && + harness.Remote.Uploaded.Count == 1, + $"dirty={harness.Core.LastLocalDirty}"); + } + + private static void Download(TestCheck check, string dataDirectory) + { + Harness harness = new(dataDirectory, "download", Local("local")); + byte[] remote = Local("remote-new"); + harness.Remote.Bytes = remote; + harness.Remote.Metadata = new WebDavFileInfo + { + ETag = "\"eN\"", + Size = remote.Length, + ModifiedUnix = 900, + }; + harness.SaveCleanState(Local("remote-old"), "\"e-old\""); + harness.MarkDirty(); + harness.Core.Decision = new SyncDecisionDto { Action = "download" }; + + SyncReport report = harness.RunAsync().GetAwaiter().GetResult(); + SyncState state = harness.State; + + check("download verifies before it replaces the live database", + harness.Events.SequenceEqual(new[] + { + "commit", "download", "verify", "write", "reload", "commit", + }), + string.Join(",", harness.Events)); + check("download applies the verified bytes", + harness.Document.Writes.Count == 1 && + harness.Document.Writes[0].SequenceEqual(remote) && + harness.Document.Reloads == 1); + check("download records the remote baseline", + state.Sha256 == Sha(remote) && state.Etag == "\"eN\"" && !state.LocalDirty && + state.RemoteModifiedUnix == 900); + check("download reports what changed", + report.Notice == SyncNotice.Downloaded && harness.LastStatus == "Synced"); + + Harness unchanged = new(dataDirectory, "download-unchanged", Local("remote-same")); + unchanged.Remote.Bytes = Local("remote-same"); + unchanged.SaveCleanState(unchanged.Remote.Bytes, "\"e1\""); + unchanged.Core.Decision = new SyncDecisionDto { Action = "download" }; + SyncReport unchangedReport = unchanged.RunAsync().GetAwaiter().GetResult(); + check("an unchanged download does not rewrite the vault", + unchanged.Document.Writes.Count == 0 && unchanged.Core.Verified.Count == 0 && + unchanged.Document.Reloads == 0 && + unchangedReport.Notice == SyncNotice.None); + } + + private static void RejectedDownload(TestCheck check, string dataDirectory) + { + Harness harness = new(dataDirectory, "rejected-download", Local("local")); + harness.Remote.Bytes = Local("corrupt-remote"); + harness.SaveCleanState(Local("remote-old"), "\"e-old\""); + harness.MarkDirty(); + harness.Core.Decision = new SyncDecisionDto { Action = "download" }; + harness.Core.VerifyFails = true; + + SyncReport report = harness.RunAsync().GetAwaiter().GetResult(); + + check("downloaded bytes that do not decrypt are rejected before writing", + report.Outcome == SyncOutcome.RemoteUnreadable && + report.Notice == SyncNotice.RemoteUnreadable && + harness.Document.Writes.Count == 0 && + harness.Remote.Uploaded.Count == 0 && + File.ReadAllBytes(harness.Document.Path).SequenceEqual(Local("local"))); + check("a rejected download leaves the baseline dirty", harness.State.LocalDirty); + } + + private static void DownloadReplaceFailure(TestCheck check, string dataDirectory) + { + Harness harness = new(dataDirectory, "replace-failure", Local("local")); + harness.Remote.Bytes = Local("remote-new"); + harness.SaveCleanState(Local("remote-old"), "\"e-old\""); + harness.MarkDirty(); + harness.Core.Decision = new SyncDecisionDto { Action = "download" }; + harness.Document.ReplaceFails = true; + + bool threw = false; + try + { + harness.RunAsync().GetAwaiter().GetResult(); + } + catch (CoreException) + { + threw = true; + } + + check("a refused local write is not followed by a clean baseline", + threw && harness.Core.Commits.Count == 1 && harness.State.LocalDirty, + $"commits={harness.Core.Commits.Count}"); + } + + private static void UploadBackoff(TestCheck check, string dataDirectory) + { + Harness harness = new(dataDirectory, "backoff", Local("local")); + harness.Remote.Bytes = Local("remote"); + harness.SaveCleanState(harness.Remote.Bytes, "\"e1\""); + harness.Core.Decision = new SyncDecisionDto { Action = "upload" }; + harness.Remote.UploadConflictsRemaining = 2; + + SyncReport report = harness.RunAsync().GetAwaiter().GetResult(); + + check("a 412 during upload retries with the back-off schedule", + report.Outcome == SyncOutcome.Synced && harness.Remote.Uploaded.Count == 1 && + harness.Time.Delays.SequenceEqual(new[] + { + TimeSpan.FromMilliseconds(500), + TimeSpan.FromMilliseconds(1500), + }), + string.Join(",", harness.Time.Delays)); + check("the retry status names the delay", + harness.StatusSources.Contains("Retrying sync in {0} ms") && + harness.Statuses.Any(update => + update.Source == "Retrying sync in {0} ms" && + update.Arguments.Length == 1 && Equals(update.Arguments[0], 500))); + check("a retried upload replays the current baseline precondition", + harness.Remote.IfMatch.Count == 1 && harness.Remote.IfMatch[0] == "\"e1\""); + } + + private static void ExhaustedUploadMerges(TestCheck check, string dataDirectory) + { + Harness harness = new(dataDirectory, "merge-auto", Local("local")); + byte[] remote = Local("remote"); + byte[] merged = Local("merged"); + harness.Remote.Bytes = remote; + harness.SaveCleanState(remote, "\"e1\""); + harness.Core.Decision = new SyncDecisionDto { Action = "upload" }; + harness.Core.MergeResult = new SyncMergeResult(merged, new List()); + harness.Document.MergeResult = harness.Core.MergeResult; + harness.Remote.UploadConflictsRemaining = 4; + + SyncReport report = harness.RunAsync().GetAwaiter().GetResult(); + SyncState state = harness.State; + + check("an upload that keeps losing 412 merges instead of overwriting", + report.Outcome == SyncOutcome.Merged && + report.Notice == SyncNotice.MergedAutomatically && + harness.Document.MergeCalls == 1 && + harness.Time.Delays.Count == 3); + check("the merge is written, uploaded and committed", + harness.Document.Writes[^1].SequenceEqual(merged) && + harness.Remote.Uploaded[^1].SequenceEqual(merged) && + harness.Events.TakeLast(7).SequenceEqual(new[] + { + "download", "verify", "merge", "write", "reload", "upload", "commit", + }), + string.Join(",", harness.Events)); + check("an automatically resolved merge records a clean baseline", + !state.LocalDirty && state.Sha256 == Sha(merged) && + harness.LastStatus == "Synced"); + check("both sides are kept as conflict copies before merging", + ConflictCopyPaths(harness).Count == 2, + string.Join("; ", ConflictCopyPaths(harness))); + } + + private static void ConflictChoices(TestCheck check, string dataDirectory) + { + static Harness Conflicted(string dataDirectory, string name, byte[] local) + { + Harness harness = new(dataDirectory, name, local); + byte[] remote = Local("remote-" + name); + harness.Remote.Bytes = remote; + harness.SaveCleanState(remote, "\"e1\""); + harness.Core.Decision = new SyncDecisionDto { Action = "conflict" }; + harness.Core.MergeResult = new SyncMergeResult( + Local("merged-" + name), + new List + { + new() + { + Uuid = "entry-1", + Kind = "both_modified", + Fields = new List { "password" }, + }, + }); + harness.Document.MergeResult = harness.Core.MergeResult; + return harness; + } + + Harness keepBoth = Conflicted(dataDirectory, "keep-both", Local("local-keep-both")); + keepBoth.Choice = SyncConflictChoice.KeepBoth; + SyncReport keepBothReport = keepBoth.RunAsync().GetAwaiter().GetResult(); + check("the conflict dialog sees both copies and the conflict fields", + keepBoth.Context is not null && + keepBoth.Context.LocalCopy is not null && + File.Exists(keepBoth.Context.LocalCopy) && + keepBoth.Context.RemoteCopy is not null && + File.Exists(keepBoth.Context.RemoteCopy) && + keepBoth.Context.Conflicts.Count == 1); + check("keeping both merges, uploads and reports the merge", + keepBothReport.Notice == SyncNotice.MergedKeptBoth && + keepBoth.LastStatus == "Merged" && + keepBoth.Remote.Uploaded[^1].SequenceEqual(keepBoth.Core.MergeResult.Bytes)); + + Harness cancel = Conflicted(dataDirectory, "cancel", Local("local-cancel")); + cancel.Choice = SyncConflictChoice.Cancel; + SyncReport cancelReport = cancel.RunAsync().GetAwaiter().GetResult(); + check("cancelling a conflict writes nothing and stays dirty", + cancelReport.Outcome == SyncOutcome.ConflictPaused && + cancel.Document.Writes.Count == 0 && cancel.State.LocalDirty && + cancel.LastStatus == "Conflict"); + + Harness keepLocal = Conflicted(dataDirectory, "keep-local", Local("local-keep")); + keepLocal.Choice = SyncConflictChoice.KeepLocal; + SyncReport keepLocalReport = keepLocal.RunAsync().GetAwaiter().GetResult(); + check("keeping local uploads the local file and leaves it untouched", + keepLocalReport.Notice == SyncNotice.KeptLocal && + keepLocal.Document.Writes.Count == 0 && + keepLocal.Remote.Uploaded[^1].SequenceEqual(Local("local-keep")) && + keepLocal.Remote.IfMatch[^1] == "\"e1\"" && !keepLocal.State.LocalDirty); + + Harness keepRemote = Conflicted(dataDirectory, "keep-remote", Local("local-remote")); + keepRemote.Choice = SyncConflictChoice.KeepRemote; + SyncReport keepRemoteReport = keepRemote.RunAsync().GetAwaiter().GetResult(); + check("keeping remote verifies, replaces and reports it", + keepRemoteReport.Notice == SyncNotice.KeptRemote && + keepRemote.Core.Verified.Count == 1 && + keepRemote.Document.Writes.Count == 1 && + keepRemote.Document.Writes[0].SequenceEqual(keepRemote.Remote.Bytes) && + !keepRemote.State.LocalDirty); + } + + private static void ConflictCopiesAreReused(TestCheck check, string dataDirectory) + { + Harness harness = new(dataDirectory, "copy-reuse", Local("local-reuse")); + byte[] remote = Local("remote-reuse"); + harness.Remote.Bytes = remote; + harness.SaveCleanState(remote, "\"e1\""); + harness.Core.Decision = new SyncDecisionDto { Action = "conflict" }; + harness.Core.MergeResult = new SyncMergeResult( + Local("merged-reuse"), + new List + { + new() { Uuid = "entry-2", Kind = "both_modified" }, + }); + harness.Document.MergeResult = harness.Core.MergeResult; + harness.Choice = SyncConflictChoice.Cancel; + + harness.RunAsync().GetAwaiter().GetResult(); + string? firstLocal = harness.Context?.LocalCopy; + string? firstRemote = harness.Context?.RemoteCopy; + harness.RunAsync().GetAwaiter().GetResult(); + + check("a repeated conflict reuses its copies instead of writing new ones", + ConflictCopyPaths(harness).Count == 2 && + harness.Context?.LocalCopy == firstLocal && + harness.Context?.RemoteCopy == firstRemote && + Directory.GetFiles(harness.Folder).Length == 3, + string.Join("; ", ConflictCopyPaths(harness))); + + // A new coordinator has no in-memory state: the deterministic names must + // still let it find the same pair after a restart. + harness.RunWithFreshCoordinatorAsync().GetAwaiter().GetResult(); + check("conflict copies are reused after a restart", + ConflictCopyPaths(harness).Count == 2 && + harness.Context?.LocalCopy == firstLocal && + harness.Context?.RemoteCopy == firstRemote && + Directory.GetFiles(harness.Folder).Length == 3, + string.Join("; ", ConflictCopyPaths(harness))); + } + + private static void LocalEditDuringSync(TestCheck check, string dataDirectory) + { + // A save that lands while the remote bytes are downloading must not be + // overwritten by the older download the decision was based on. + Harness download = new(dataDirectory, "edit-during-download", Local("baseline")); + byte[] remote = Local("remote"); + download.Remote.Bytes = remote; + download.Remote.Metadata = new WebDavFileInfo + { + ETag = "\"e2\"", + Size = remote.Length, + ModifiedUnix = 700, + }; + download.SaveCleanState(Local("baseline"), "\"e1\""); + download.Core.Decision = new SyncDecisionDto { Action = "download" }; + byte[] userEdit = Local("user-edit"); + download.Remote.OnDownload = + () => download.Document.ReplaceAsync(userEdit).GetAwaiter().GetResult(); + + SyncReport report = download.RunAsync().GetAwaiter().GetResult(); + check("sync: a save during a download pauses instead of being overwritten", + report.Outcome == SyncOutcome.ConflictPaused && + report.Notice == SyncNotice.LocalChangedWhileSyncing && + download.Document.Bytes.SequenceEqual(userEdit) && + download.Document.Writes.Count == 1 && download.State.LocalDirty, + report.Notice.ToString()); + check("sync: the paused download uploads nothing and says why", + download.Remote.Uploaded.Count == 0 && download.LastStatus == "Local changed", + download.LastStatus); + + // Same race while a merge result is being prepared. + Harness merge = new(dataDirectory, "edit-during-merge", Local("baseline")); + merge.Remote.Bytes = Local("remote"); + merge.SaveCleanState(Local("baseline"), "\"e1\""); + merge.Core.Decision = new SyncDecisionDto { Action = "download_and_merge" }; + merge.Core.MergeResult = new SyncMergeResult(Local("merged"), + new List()); + merge.Document.MergeResult = merge.Core.MergeResult; + byte[] mergeEdit = Local("merge-user-edit"); + merge.Remote.OnDownload = + () => merge.Document.ReplaceAsync(mergeEdit).GetAwaiter().GetResult(); + + SyncReport mergeReport = merge.RunAsync().GetAwaiter().GetResult(); + check("sync: a save during a merge pauses instead of applying the older result", + mergeReport.Outcome == SyncOutcome.ConflictPaused && + mergeReport.Notice == SyncNotice.LocalChangedWhileSyncing && + merge.Document.Bytes.SequenceEqual(mergeEdit) && + merge.Document.Writes.Count == 1 && merge.State.LocalDirty, + mergeReport.Notice.ToString()); + } + + private static void LocalEditDuringUpload(TestCheck check, string dataDirectory) + { + // A save that lands while the core is serializing the upload snapshot + // must not be overwritten by that older snapshot. + Harness harness = new(dataDirectory, "edit-during-upload", Local("baseline")); + harness.Remote.Missing = true; + harness.Core.ModelBytes = Local("model"); + byte[] userEdit = Local("upload-user-edit"); + harness.Core.OnSaveBytes = + () => harness.Document.ReplaceAsync(userEdit).GetAwaiter().GetResult(); + + SyncReport report = harness.RunAsync().GetAwaiter().GetResult(); + check("sync: a save during the upload snapshot pauses instead of being overwritten", + report.Outcome == SyncOutcome.ConflictPaused && + report.Notice == SyncNotice.LocalChangedWhileSyncing && + harness.Document.Bytes.SequenceEqual(userEdit) && + harness.Remote.Uploaded.Count == 0 && harness.State.LocalDirty, + report.Notice.ToString()); + } + + private static void UnreadableRemote(TestCheck check, string dataDirectory) + { + Harness paused = new(dataDirectory, "unreadable-remote-paused", Local("local")); + paused.Remote.Bytes = Local("corrupt-remote"); + paused.SaveCleanState(Local("remote-old"), "\"e1\""); + paused.MarkDirty(); + paused.Core.Decision = new SyncDecisionDto { Action = "download" }; + paused.Core.VerifyFails = true; + + SyncReport pausedReport = paused.RunAsync().GetAwaiter().GetResult(); + string? preserved = pausedReport.RemoteCopy; + check("sync: an unreadable remote copy never replaces the local vault", + pausedReport.Outcome == SyncOutcome.RemoteUnreadable && + pausedReport.Notice == SyncNotice.RemoteUnreadable && + paused.Document.Writes.Count == 0 && paused.Remote.Uploaded.Count == 0 && + paused.State.LocalDirty, + pausedReport.Notice.ToString()); + check("sync: the unreadable remote bytes are preserved next to the vault", + preserved is not null && File.Exists(preserved) && + File.ReadAllBytes(preserved).SequenceEqual(Local("corrupt-remote")), + preserved ?? "not preserved"); + + Harness repaired = new(dataDirectory, "unreadable-remote-repair", Local("local")); + repaired.Remote.Bytes = Local("corrupt-remote"); + repaired.SaveCleanState(Local("remote-old"), "\"e1\""); + repaired.MarkDirty(); + repaired.Core.Decision = new SyncDecisionDto { Action = "download" }; + repaired.Core.VerifyFails = true; + repaired.Coordinator.OverwriteUnreadableRemote = true; + + SyncReport repairedReport = repaired.RunAsync().GetAwaiter().GetResult(); + check("sync: an explicit repair uploads the local copy over an unreadable remote", + repairedReport.Outcome == SyncOutcome.Synced && + repairedReport.Notice == SyncNotice.RemoteRepaired && + repaired.Remote.Uploaded.Count == 1 && + repaired.Remote.Uploaded[0].SequenceEqual(Local("local")) && + !repaired.State.LocalDirty && + repaired.State.Sha256 == Sha(Local("local")) && + repairedReport.RemoteCopy is not null && + File.Exists(repairedReport.RemoteCopy), + repairedReport.Notice.ToString()); + } + + private static void NothingQueued(TestCheck check, string dataDirectory) + { + Harness offline = new(dataDirectory, "offline", Local("local-offline")); + offline.Core.Decision = new SyncDecisionDto + { + Action = "offline", + Reason = "network down", + }; + SyncReport offlineReport = offline.RunAsync().GetAwaiter().GetResult(); + check("an offline decision writes nothing and says offline", + offlineReport.Outcome == SyncOutcome.Offline && + offlineReport.Reason == "network down" && + offline.Document.Writes.Count == 0 && + offline.Core.Commits.Count == 0 && offline.LastStatus == "Offline"); + + Harness retry = new(dataDirectory, "retry", Local("local-retry")); + retry.Core.Decision = new SyncDecisionDto { Action = "retry" }; + SyncReport retryReport = retry.RunAsync().GetAwaiter().GetResult(); + check("a retry decision writes nothing and reports retry", + retryReport.Outcome == SyncOutcome.Retry && + retry.Document.Writes.Count == 0 && retry.LastStatus == "Sync retry"); + + Harness dirty = new(dataDirectory, "decision-inputs", Local("local-dirty")); + dirty.Remote.Bytes = Local("remote-dirty"); + dirty.SaveCleanState(Local("remote-old-dirty"), "\"e-old\""); + dirty.MarkDirty(); + dirty.Remote.Metadata = new WebDavFileInfo + { + ETag = "\"e-mark\"", + Size = 3, + ModifiedUnix = 42, + }; + dirty.Core.Decision = new SyncDecisionDto { Action = "up_to_date" }; + dirty.RunAsync().GetAwaiter().GetResult(); + check("the decision receives the persisted dirty flag and remote metadata", + dirty.Core.LastLocalDirty && + dirty.Core.LastRemoteMeta?.Contains("e-mark", StringComparison.Ordinal) == true && + dirty.Core.LastRemoteMeta?.Contains("\"modified_unix\":42", StringComparison.Ordinal) == true, + dirty.Core.LastRemoteMeta ?? string.Empty); + } + + // ------------------------------------------------------------------ helpers + + private static byte[] Local(string value) + => System.Text.Encoding.UTF8.GetBytes("kdbx-" + value); + + private static string Sha(byte[] bytes) + => Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(); + + private static List ConflictCopyPaths(Harness harness) + => Directory.GetFiles(harness.Folder) + .Where(path => Path.GetFileName(path).Contains("(conflict ", StringComparison.Ordinal) || + Path.GetFileName(path).Contains("(remote conflict ", StringComparison.Ordinal)) + .OrderBy(path => path, StringComparer.Ordinal) + .ToList(); + + private sealed class Harness + { + private readonly List _events = new(); + + public Harness(string dataDirectory, string name, byte[] localBytes) + { + Folder = Path.Combine(dataDirectory, + "sync-" + name + "-" + Guid.NewGuid().ToString("N")[..8]); + System.IO.Directory.CreateDirectory(Folder); + Document = new FakeDocument(Path.Combine(Folder, "vault.kdbx"), localBytes) + { + Events = _events, + }; + Remote = new FakeRemote { Events = _events }; + Core = new FakeCore(_events); + Time = new ImmediateDelay(); + States = new SyncStateStore(Path.Combine(Folder, "state")); + Coordinator = new SyncCoordinator(States, Time.DelayAsync) + { + ConflictChoice = AnswerConflict, + }; + } + + public string Folder { get; } + + public FakeDocument Document { get; } + + public FakeRemote Remote { get; } + + public FakeCore Core { get; } + + public ImmediateDelay Time { get; } + + public SyncStateStore States { get; } + + public SyncCoordinator Coordinator { get; } + + public List Statuses { get; } = new(); + + public List Events => _events; + + public SyncConflictChoice Choice { get; set; } = SyncConflictChoice.Cancel; + + public SyncConflictContext? Context { get; private set; } + + public string LastStatus => Statuses.Count == 0 ? "" : Statuses[^1].Source; + + public IEnumerable StatusSources => Statuses.Select(update => update.Source); + + public SyncState State => States.Load(Url, User, Document.Path); + + public Task RunAsync() + => Coordinator.RunAsync( + Remote, + Document, + Core, + new SyncOptions + { + RemoteUrl = Url, + Username = User, + MasterPassword = Password, + }, + update => Statuses.Add(update)); + + /// Run once with a coordinator that has no in-memory state. + public Task RunWithFreshCoordinatorAsync() + { + var coordinator = new SyncCoordinator(States, Time.DelayAsync) + { + ConflictChoice = AnswerConflict, + }; + return coordinator.RunAsync( + Remote, + Document, + Core, + new SyncOptions + { + RemoteUrl = Url, + Username = User, + MasterPassword = Password, + }, + update => Statuses.Add(update)); + } + + public void SaveCleanState(byte[] remoteBytes, string etag) + => States.Save(Url, User, Document.Path, new SyncState + { + Etag = etag, + Sha256 = Sha(remoteBytes), + Size = remoteBytes.Length, + RemoteModifiedUnix = 100, + LocalDirty = false, + }); + + public void MarkDirty() + { + SyncState state = States.Load(Url, User, Document.Path); + state.LocalDirty = true; + States.Save(Url, User, Document.Path, state); + } + + private Task AnswerConflict(SyncConflictContext context) + { + Context = context; + return Task.FromResult(Choice); + } + } + + private sealed class FakeRemote : ISyncRemote + { + public List? Events { get; init; } + + public WebDavFileInfo? Metadata { get; set; } = new() + { + ETag = "\"e1\"", + Size = 3, + ModifiedUnix = 100, + }; + + public byte[] Bytes { get; set; } = new byte[] { 1, 2, 3 }; + + public bool Missing { get; set; } + + public int UploadConflictsRemaining { get; set; } + + public List Uploaded { get; } = new(); + + public List IfMatch { get; } = new(); + + public int Downloads { get; private set; } + + /// Hook to simulate a local save while the download is in flight. + public Action? OnDownload { get; set; } + + public Task GetMetadataAsync(CancellationToken cancellationToken = default) + => Task.FromResult(Missing ? null : Metadata); + + public Task DownloadAsync(CancellationToken cancellationToken = default) + { + Downloads++; + Events?.Add("download"); + OnDownload?.Invoke(); + return Task.FromResult(Bytes); + } + + public Task UploadAsync(byte[] bytes, string? ifMatch, + CancellationToken cancellationToken = default) + { + if (UploadConflictsRemaining > 0) + { + UploadConflictsRemaining--; + throw new WebDavException("the remote changed", 412, conflict: true); + } + Events?.Add("upload"); + Uploaded.Add(bytes); + IfMatch.Add(ifMatch); + Bytes = bytes; + Metadata = new WebDavFileInfo + { + ETag = "\"e" + (Uploaded.Count + 1) + "\"", + Size = bytes.Length, + ModifiedUnix = 200 + Uploaded.Count, + }; + return Task.FromResult(Metadata?.ETag); + } + } + + private sealed class FakeCore : ICoreClient + { + public Task GetDatabaseInfoAsync() + => Task.FromResult(new DatabaseInfoDto()); + + public Task SetKdfAsync(string preset) + => Task.FromResult(new DatabaseInfoDto()); + + public FakeCore(List? events = null) + { + Events = events; + } + + public List? Events { get; } + + public SyncDecisionDto Decision { get; set; } = new() { Action = "upload" }; + + public byte[] ModelBytes { get; set; } = new byte[] { 9, 9, 9 }; + + public SyncMergeResult MergeResult { get; set; } = + new(Array.Empty(), new List()); + + public bool VerifyFails { get; set; } + + public List<(string? Etag, string? Sha)> Commits { get; } = new(); + + public List Verified { get; } = new(); + + public string? LastRemoteMeta { get; private set; } + + public bool LastLocalDirty { get; private set; } + + public bool IsOpen => true; + + public string? DatabasePath { get; set; } + + public Task OpenAsync(string path, string password) + => throw new NotSupportedException(); + + public Task OpenBytesAsync(byte[] kdbx, string password, string? databasePath = null) + => throw new NotSupportedException(); + + public Task LockAsync() => Task.CompletedTask; + + public Task SaveBytesAsync() + { + OnSaveBytes?.Invoke(); + return Task.FromResult(ModelBytes); + } + + /// Hook to simulate a local save while the snapshot is taken. + public Action? OnSaveBytes { get; set; } + + public Task SaveAsync(string path, int backupRetention = 20, + Func? databaseChanged = null) + => throw new NotSupportedException(); + + public Task VerifyAsync(byte[] bytes, string password) + { + if (VerifyFails) + { + throw new CoreException("Corrupt", "downloaded bytes do not decrypt"); + } + Verified.Add(bytes); + Events?.Add("verify"); + return Task.CompletedTask; + } + + public Task SyncDecideAsync(string remoteMetaJson, bool localDirty) + { + LastRemoteMeta = remoteMetaJson; + LastLocalDirty = localDirty; + return Task.FromResult(Decision); + } + + public Task SyncCommitAsync(string? etag, string? sha256) + { + Commits.Add((etag, sha256)); + Events?.Add("commit"); + return Task.CompletedTask; + } + + public void Dispose() + { + } + } + + private sealed class FakeDocument : IVaultDocument + { + public FakeDocument(string path, byte[] bytes) + { + Path = path; + Bytes = bytes; + File.WriteAllBytes(path, bytes); + } + + public string Path { get; } + + public byte[] Bytes { get; private set; } + + public List? Events { get; init; } + + public bool ReplaceFails { get; set; } + + public List Writes { get; } = new(); + + public int Reloads { get; private set; } + + public int MergeCalls { get; private set; } + + public SyncMergeResult MergeResult { get; set; } = + new(Array.Empty(), new List()); + + public Task ReadBytesAsync() => Task.FromResult(Bytes); + + public Task ReplaceAsync(byte[] bytes) + { + if (ReplaceFails) + { + throw new CoreException("VaultChanged", "the file changed outside"); + } + Writes.Add(bytes); + Bytes = bytes; + File.WriteAllBytes(Path, bytes); + Events?.Add("write"); + return Task.CompletedTask; + } + + public Task ReloadAsync() + { + Reloads++; + Events?.Add("reload"); + return Task.CompletedTask; + } + + public Task MergeRemoteAsync(byte[] remote) + { + MergeCalls++; + Events?.Add("merge"); + return Task.FromResult(MergeResult); + } + } + + private sealed class ImmediateDelay + { + public List Delays { get; } = new(); + + public Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken) + { + Delays.Add(delay); + return cancellationToken.IsCancellationRequested + ? Task.FromCanceled(cancellationToken) + : Task.CompletedTask; + } + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/SyncStateStoreTests.cs b/tests/app-core/Keepassity.Core.Tests/SyncStateStoreTests.cs new file mode 100644 index 0000000..1d67957 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/SyncStateStoreTests.cs @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// Headless checks for the sync baseline sidecar: round trip, malformed hash +/// fails closed, and an unreadable sidecar is preserved for diagnosis. +/// +internal static class SyncStateStoreTests +{ + public static void Run(TestCheck check, string rootDirectory) + { + string directory = Path.Combine(rootDirectory, "sync-state"); + Directory.CreateDirectory(directory); + var store = new SyncStateStore(directory); + check("sync state: store available", store.Available); + + var state = new SyncState + { + Etag = "\"etag-1\"", + Sha256 = new string('a', 64), + Size = 1234, + RemoteModifiedUnix = 1_700_000_000, + LocalDirty = false, + }; + store.Save("https://dav.example.test/db.kdbx", "user", "/tmp/db.kdbx", state); + SyncState loaded = store.Load("https://dav.example.test/db.kdbx", "user", "/tmp/db.kdbx"); + check("sync state: round trip", loaded.Etag == "\"etag-1\"" && + loaded.Sha256 == new string('a', 64) && loaded.Size == 1234 && + !loaded.LocalDirty, loaded.Etag ?? "null"); + + SyncState missing = store.Load("https://dav.example.test/other.kdbx", "user", + "/tmp/other.kdbx"); + check("sync state: missing baseline is clean", !missing.LocalDirty); + + state.Sha256 = "not-a-sha"; + store.Save("https://dav.example.test/bad.kdbx", "user", "/tmp/bad.kdbx", state); + SyncState malformed = store.Load("https://dav.example.test/bad.kdbx", "user", + "/tmp/bad.kdbx"); + check("sync state: malformed hash fails closed", malformed.LocalDirty); + + string corruptDirectory = Path.Combine(rootDirectory, "sync-state-corrupt"); + Directory.CreateDirectory(corruptDirectory); + var corruptStore = new SyncStateStore(corruptDirectory); + corruptStore.Save("https://dav.example.test/corrupt.kdbx", "user", + "/tmp/corrupt.kdbx", state); + string? anySidecar = Directory.GetFiles(corruptDirectory, "*.json").FirstOrDefault(); + check("sync state: sidecar written", anySidecar is not null); + if (anySidecar is not null) + { + File.WriteAllText(anySidecar, "{ not json"); + SyncState corrupt = corruptStore.Load("https://dav.example.test/corrupt.kdbx", + "user", "/tmp/corrupt.kdbx"); + check("sync state: corrupt sidecar is dirty", corrupt.LocalDirty); + check("sync state: corrupt sidecar is preserved", + Directory.GetFiles(corruptDirectory, "*.corrupt-*").Length > 0); + } + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/SyncStatusViewModelTests.cs b/tests/app-core/Keepassity.Core.Tests/SyncStatusViewModelTests.cs new file mode 100644 index 0000000..19f9036 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/SyncStatusViewModelTests.cs @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Headless behaviour checks for the sync status view model. +using Keepassity.ViewModels; + +namespace Keepassity.CoreTests; + +internal static class SyncStatusViewModelTests +{ + public static void Run(TestCheck check) + { + var text = new SwitchingText(); + var vm = new SyncStatusViewModel(text); + check("sync status starts as local only", vm.Text == "Local only", vm.Text); + + vm.Set("Synced"); + check("sync status renders a plain status", vm.Text == "Synced", vm.Text); + + vm.Set("Retrying sync in {0} ms", 1500); + check("sync status formats numeric arguments", + vm.Text == "Retrying sync in 1500 ms", vm.Text); + + text.Language = "zh-CN"; + vm.Refresh(); + check("sync status refreshes after a language change", + vm.Text == "[zh-CN] Retrying sync in 1500 ms", vm.Text); + check("sync status keeps its source for diagnostics", vm.Source == "Retrying sync in {0} ms"); + } + + private sealed class SwitchingText : IAppText + { + public string Language { get; set; } = "en"; + + public string T(string english) + => Language == "en" ? english : $"[{Language}] {english}"; + + public string T(string format, params object?[] arguments) + { + string text = arguments.Length == 0 ? format : string.Format(format, arguments); + return Language == "en" ? text : $"[{Language}] {text}"; + } + + public string TLong(string key, string english) + => Language == "en" ? english : $"[{Language}] {english}"; + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/TotpDisplayViewModelTests.cs b/tests/app-core/Keepassity.Core.Tests/TotpDisplayViewModelTests.cs new file mode 100644 index 0000000..ef9d25b --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/TotpDisplayViewModelTests.cs @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.ViewModels; + +namespace Keepassity.CoreTests; + +/// +/// Headless checks for the TOTP display state machine: code activation, +/// countdown, window rollover, unavailable state, entry switch and prefetch. +/// +internal static class TotpDisplayViewModelTests +{ + private sealed class FakeSource : ITotpCodeSource + { + public Func Handler { get; set; } = + (_, _) => new TotpCodeSnapshot("123456", 30, 30, 6); + public List<(string Uuid, long? At)> Calls { get; } = new(); + + public Task GetAsync(string uuid, long? atUnix) + { + Calls.Add((uuid, atUnix)); + return Task.FromResult(Handler(uuid, atUnix)); + } + } + + public static void Run(TestCheck check) + { + RunBasicWindow(check); + RunPrefetch(check); + RunUnavailableAndReset(check); + RunSourceFailure(check); + } + + private static void RunBasicWindow(TestCheck check) + { + long now = 1_000; + var source = new FakeSource(); + var totp = new TotpDisplayViewModel(source, () => now); + totp.SelectEntry("entry-a"); + totp.TickAsync().GetAwaiter().GetResult(); + check("totp display: code activated", totp.HasCode && totp.CodeText == "123 456" && + totp.CurrentCode == "123456", totp.CodeText); + check("totp display: initial countdown", totp.RemainingSeconds == 30 && + totp.Period == 30 && totp.ProgressValue == 0, + $"{totp.RemainingSeconds}/{totp.ProgressValue}"); + check("totp display: one source request", source.Calls.Count == 1, + source.Calls.Count.ToString()); + + now += 10; + totp.TickAsync().GetAwaiter().GetResult(); + check("totp display: countdown advances", totp.RemainingSeconds == 20 && + totp.ProgressValue == 10, totp.RemainingSeconds.ToString()); + check("totp display: displayed code is not re-requested", + source.Calls.Count == 1, source.Calls.Count.ToString()); + + now += 20; + totp.TickAsync().GetAwaiter().GetResult(); + check("totp display: window rollover requests a new code", + source.Calls.Count >= 2, source.Calls.Count.ToString()); + } + + private static void RunPrefetch(TestCheck check) + { + long now = 2_000; + var source = new FakeSource + { + Handler = (_, at) => at is null + ? new TotpCodeSnapshot("111111", 5, 5, 6) + : new TotpCodeSnapshot("222222", 5, 5, 6), + }; + var totp = new TotpDisplayViewModel(source, () => now); + totp.SelectEntry("entry-prefetch"); + totp.TickAsync().GetAwaiter().GetResult(); + now += 3; // two seconds remain, prefetch threshold + totp.TickAsync().GetAwaiter().GetResult(); + // Let the fire-and-forget prefetch finish. + Task.Delay(50).GetAwaiter().GetResult(); + int callsBeforeBoundary = source.Calls.Count; + now += 2; + totp.TickAsync().GetAwaiter().GetResult(); + check("totp display: prefetched code is adopted at the boundary", + totp.CodeText == "222 222", totp.CodeText); + check("totp display: boundary did not need another request", + source.Calls.Count == callsBeforeBoundary, source.Calls.Count.ToString()); + } + + private static void RunSourceFailure(TestCheck check) + { + long now = 4_000; + var source = new FakeSource(); + var totp = new TotpDisplayViewModel(source, () => now); + totp.SelectEntry("entry-fail"); + source.Handler = (_, _) => throw new InvalidOperationException("the core is locked"); + bool escaped = false; + try + { + totp.TickAsync().GetAwaiter().GetResult(); + } + catch + { + escaped = true; + } + check("totp display: a failing source does not escape the tick", !escaped); + check("totp display: a failing source is shown as unavailable", + !totp.HasCode && totp.SourceFailed); + + source.Handler = (_, _) => new TotpCodeSnapshot("777777", 30, 30, 6); + now += 1; + totp.TickAsync().GetAwaiter().GetResult(); + check("totp display: the next successful tick clears the failure", + totp.HasCode && !totp.SourceFailed && totp.CodeText == "777 777", + totp.CodeText); + } + + private static void RunUnavailableAndReset(TestCheck check) + { + long now = 3_000; + var source = new FakeSource { Handler = (_, _) => null }; + var totp = new TotpDisplayViewModel(source, () => now); + totp.SelectEntry("entry-none"); + totp.TickAsync().GetAwaiter().GetResult(); + check("totp display: missing code is unavailable", + !totp.HasCode && totp.CodeText.Length == 0); + check("totp display: a missing code is not a source failure", + !totp.SourceFailed); + totp.Reset(); + check("totp display: reset clears state", !totp.HasCode && + totp.RemainingSeconds == 0 && totp.CurrentCode is null); + + source.Handler = (_, _) => new TotpCodeSnapshot("654321", 30, 30, 6); + totp.SelectEntry("entry-a"); + totp.TickAsync().GetAwaiter().GetResult(); + totp.SelectEntry("entry-b"); + check("totp display: entry switch hides the old code", !totp.HasCode); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/TotpTimingTests.cs b/tests/app-core/Keepassity.Core.Tests/TotpTimingTests.cs new file mode 100644 index 0000000..6d3d17b --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/TotpTimingTests.cs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.ViewModels; + +namespace Keepassity.CoreTests; + +/// +/// Headless checks for the TOTP countdown boundary: clamping, formatting, the +/// request/prefetch decisions and the timer interval near a window end. +/// +internal static class TotpTimingTests +{ + public static void Run(TestCheck check) + { + check("totp: remaining in window", TotpTiming.Remaining(100, 70, 30) == 30); + check("totp: remaining clamps at zero", TotpTiming.Remaining(100, 130, 30) == 0); + check("totp: remaining clamps at period", TotpTiming.Remaining(100, 0, 30) == 30); + check("totp: period is at least one", TotpTiming.Remaining(100, 99, 0) == 1); + + check("totp: format six digits", TotpTiming.FormatCode("123456", 6) == "123 456"); + check("totp: format eight digits", TotpTiming.FormatCode("12345678", 8) == "1234 5678"); + check("totp: format unknown length", TotpTiming.FormatCode("12345", 6) == "12345"); + + check("totp: requests when no code", TotpTiming.ShouldRequestCode( + 50, false, null, "uuid-a", long.MaxValue)); + check("totp: requests on entry change", TotpTiming.ShouldRequestCode( + 50, true, "uuid-a", "uuid-b", 100)); + check("totp: requests after window end", TotpTiming.ShouldRequestCode( + 100, true, "uuid-a", "uuid-a", 100)); + check("totp: keeps code inside window", !TotpTiming.ShouldRequestCode( + 99, true, "uuid-a", "uuid-a", 100)); + + check("totp: prefetch under three seconds", TotpTiming.ShouldPrefetch( + 2, 100, false, false)); + check("totp: no prefetch at three seconds", !TotpTiming.ShouldPrefetch( + 3, 100, false, false)); + check("totp: no prefetch while one is pending", !TotpTiming.ShouldPrefetch( + 1, 100, false, true)); + check("totp: no prefetch for an unbounded window", !TotpTiming.ShouldPrefetch( + 1, long.MaxValue, false, false)); + + check("totp: timer snaps to a near boundary", + TotpTiming.NextTick(TimeSpan.FromMilliseconds(500)) == + TimeSpan.FromMilliseconds(515), + TotpTiming.NextTick(TimeSpan.FromMilliseconds(500)).ToString()); + check("totp: timer uses one second away from a boundary", + TotpTiming.NextTick(TimeSpan.FromSeconds(2)) == TimeSpan.FromSeconds(1)); + check("totp: timer uses one second at the boundary", + TotpTiming.NextTick(TimeSpan.Zero) == TimeSpan.FromSeconds(1)); + + check("totp: prefetch usable at window start", + TotpTiming.IsPrefetchUsable(100, 30, 100)); + check("totp: prefetch unusable before its window", + !TotpTiming.IsPrefetchUsable(100, 30, 99)); + check("totp: prefetch unusable after its window", + !TotpTiming.IsPrefetchUsable(100, 30, 130)); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/UnlockViewModelTests.cs b/tests/app-core/Keepassity.Core.Tests/UnlockViewModelTests.cs new file mode 100644 index 0000000..6588a81 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/UnlockViewModelTests.cs @@ -0,0 +1,343 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Behavioural checks for the first MVVM view model. These run headless and never +// load WinUI or the native library. +using Keepassity.Core; +using Keepassity.ViewModels; + +namespace Keepassity.CoreTests; + +internal static class UnlockViewModelTests +{ + private static Action _report = (_, _, _) => { }; + + private static void Check(string name, bool ok) => _report(name, ok, string.Empty); + + private static void Check(string name, bool ok, string detail) => _report(name, ok, detail); + + public static void Run(Action check, string dataDirectory) + { + _report = check; + MissingDatabaseIsRejected(); + EmptyPasswordIsRejected(); + WrongPasswordIsClassified(); + CorruptDatabaseIsClassified(); + UnsupportedDatabaseIsClassified(); + SuccessClearsTheBanner(); + ConcurrentAttemptsAreRejected(); + ChangingTheDatabaseClearsStaleErrors(); + PendingRemoteDownloadOpensItsBytesFirst(dataDirectory); + PendingRemoteDownloadSurvivesAWrongPassword(dataDirectory); + } + + private static void MissingDatabaseIsRejected() + { + var core = new FakeCoreClient(); + var vm = new UnlockViewModel(core, FakeText.Instance); + bool unlocked = vm.UnlockAsync("secret").GetAwaiter().GetResult(); + Check("unlock rejects a missing database", !unlocked); + Check("unlock missing database shows a message", + vm.IsStatusOpen && vm.StatusTitle == "Cannot open database" && + vm.StatusMessage == "Choose a .kdbx database first." && + vm.StatusSeverity == UnlockStatusSeverity.Error && !vm.RecoveryVisible, + $"{vm.StatusTitle} / {vm.StatusMessage}"); + Check("unlock missing database never opens the core", core.OpenCalls == 0); + } + + private static void EmptyPasswordIsRejected() + { + var core = new FakeCoreClient(); + var vm = new UnlockViewModel(core, FakeText.Instance); + vm.SetDatabasePath(@"C:\vault.kdbx"); + bool unlocked = vm.UnlockAsync(string.Empty).GetAwaiter().GetResult(); + Check("unlock rejects an empty password", !unlocked); + Check("unlock empty password shows a message", + vm.IsStatusOpen && vm.StatusMessage == "Enter the master password.", + vm.StatusMessage); + Check("unlock empty password never opens the core", core.OpenCalls == 0); + } + + private static void WrongPasswordIsClassified() + { + var core = new FakeCoreClient + { + OnOpen = (_, _) => Task.FromException(new CoreException("BadPassword", "bad password")), + }; + var vm = new UnlockViewModel(core, FakeText.Instance); + vm.SetDatabasePath(@"C:\vault.kdbx"); + bool unlocked = vm.UnlockAsync("wrong").GetAwaiter().GetResult(); + Check("unlock reports a wrong password", !unlocked); + Check("wrong password uses its own title", + vm.StatusTitle == "Wrong master password" && vm.RecoveryVisible, + vm.StatusTitle); + Check("wrong password leaves the busy state", !vm.IsBusy && vm.CanUnlock); + } + + private static void CorruptDatabaseIsClassified() + { + var core = new FakeCoreClient + { + OnOpen = (_, _) => Task.FromException( + new CoreException("CorruptDatabase", "damaged")), + }; + var vm = new UnlockViewModel(core, FakeText.Instance); + vm.SetDatabasePath(@"C:\vault.kdbx"); + bool unlocked = vm.UnlockAsync("secret").GetAwaiter().GetResult(); + Check("unlock reports a damaged database", !unlocked); + Check("damaged database keeps its core error code", + vm.LastErrorCode == "CorruptDatabase", vm.LastErrorCode ?? "(none)"); + Check("damaged database uses its own title", + vm.StatusTitle == "Database is damaged" && vm.RecoveryVisible, + vm.StatusTitle); + } + + private static void UnsupportedDatabaseIsClassified() + { + var core = new FakeCoreClient + { + OnOpen = (_, _) => Task.FromException( + new CoreException("UnsupportedFormat", "unsupported")), + }; + var vm = new UnlockViewModel(core, FakeText.Instance); + vm.SetDatabasePath(@"C:\vault.kdbx"); + _ = vm.UnlockAsync("secret").GetAwaiter().GetResult(); + Check("unsupported database uses its own title", + vm.StatusTitle == "Unsupported database", vm.StatusTitle); + } + + private static void SuccessClearsTheBanner() + { + var core = new FakeCoreClient(); + var vm = new UnlockViewModel(core, FakeText.Instance); + vm.SetDatabasePath(@"C:\vault.kdbx"); + // Seed a stale error, which a successful unlock must clear. + _ = vm.UnlockAsync(string.Empty).GetAwaiter().GetResult(); + bool unlocked = vm.UnlockAsync("correct").GetAwaiter().GetResult(); + Check("unlock succeeds for the right password", unlocked); + Check("successful unlock clears the status banner", + !vm.IsStatusOpen && vm.StatusMessage.Length == 0 && !vm.RecoveryVisible); + Check("successful unlock passes the selected path and password", + core.OpenedPath == @"C:\vault.kdbx" && core.OpenedPassword == "correct"); + Check("successful unlock clears the last error code", vm.LastErrorCode is null, + vm.LastErrorCode ?? "(none)"); + Check("successful unlock leaves the view model idle", !vm.IsBusy && vm.CanUnlock); + } + + private static void ConcurrentAttemptsAreRejected() + { + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var core = new FakeCoreClient + { + OnOpen = async (_, _) => await gate.Task.ConfigureAwait(false), + }; + var vm = new UnlockViewModel(core, FakeText.Instance); + vm.SetDatabasePath(@"C:\vault.kdbx"); + Task first = vm.UnlockAsync("correct"); + Check("unlock sets the busy state before awaiting", + vm.IsBusy && !vm.CanUnlock && !vm.IsInputEnabled); + bool second = vm.UnlockAsync("again").GetAwaiter().GetResult(); + Check("a second unlock while busy is ignored", !second); + Check("a busy unlock does not reach the core twice", core.OpenCalls == 1, + core.OpenCalls.ToString()); + gate.SetResult(); + Check("the in-flight unlock completes", first.GetAwaiter().GetResult()); + Check("the view model returns to idle", !vm.IsBusy && vm.CanUnlock); + } + + private static void ChangingTheDatabaseClearsStaleErrors() + { + var core = new FakeCoreClient + { + OnOpen = (_, _) => Task.FromException(new CoreException("BadPassword", "bad")), + }; + var vm = new UnlockViewModel(core, FakeText.Instance); + vm.SetDatabasePath(@"C:\first.kdbx"); + _ = vm.UnlockAsync("wrong").GetAwaiter().GetResult(); + Check("a failed unlock is visible before switching", vm.IsStatusOpen); + vm.SetDatabasePath(@"C:\second.kdbx"); + Check("switching databases clears the stale error", + !vm.IsStatusOpen && !vm.RecoveryVisible && vm.HasDatabase); + } + + /// + /// A WebDAV download is opened from its bytes, so the working copy is only + /// rewritten after the master password proved that the download decrypts. + /// + private static void PendingRemoteDownloadOpensItsBytesFirst(string dataDirectory) + { + string folder = NewFolder(dataDirectory, "pending-promote"); + string workingCopy = Path.Combine(folder, "vault.kdbx"); + byte[] oldBytes = { 1, 1, 1 }; + byte[] pendingBytes = { 7, 7, 7, 7 }; + File.WriteAllBytes(workingCopy, oldBytes); + var states = new SyncStateStore(Path.Combine(folder, "state")); + var core = new FakeCoreClient(); + var vm = new UnlockViewModel(core, FakeText.Instance, new RemoteVaultOpener(states)); + vm.SetDatabasePath(workingCopy); + vm.SetPendingRemote(Pending(url: "https://example.test/pending.kdbx", workingCopy, + pendingBytes)); + + bool unlocked = vm.UnlockAsync("correct").GetAwaiter().GetResult(); + + Check("a pending remote download unlocks its bytes", + unlocked && core.OpenBytesCalls == 1, core.OpenBytesCalls.ToString()); + Check("a pending remote download never opens the stale path", core.OpenCalls == 0); + Check("promoting a pending download writes the verified bytes", + File.ReadAllBytes(workingCopy).SequenceEqual(pendingBytes)); + Check("a promoted pending download is forgotten", vm.PendingRemote is null); + SyncState state = states.Load("https://example.test/pending.kdbx", "user", + workingCopy); + Check("promoting a pending download records a clean baseline", + !state.LocalDirty && state.Etag == "\"e1\"" && + state.Sha256 == Sha(pendingBytes), state.Sha256 ?? "(none)"); + } + + private static void PendingRemoteDownloadSurvivesAWrongPassword(string dataDirectory) + { + string folder = NewFolder(dataDirectory, "pending-retry"); + string workingCopy = Path.Combine(folder, "vault.kdbx"); + byte[] oldBytes = { 2, 2, 2 }; + byte[] pendingBytes = { 8, 8 }; + File.WriteAllBytes(workingCopy, oldBytes); + var states = new SyncStateStore(Path.Combine(folder, "state")); + var core = new FakeCoreClient + { + OnOpenBytes = (_, _, _) => Task.FromException( + new CoreException("BadPassword", "incorrect master password")), + }; + var vm = new UnlockViewModel(core, FakeText.Instance, new RemoteVaultOpener(states)); + vm.SetDatabasePath(workingCopy); + vm.SetPendingRemote(Pending(url: "https://example.test/retry.kdbx", workingCopy, + pendingBytes)); + + bool unlocked = vm.UnlockAsync("wrong").GetAwaiter().GetResult(); + + Check("a wrong password rejects the pending download", !unlocked); + Check("a wrong password uses the wrong-password title", + vm.StatusTitle == "Wrong master password", vm.StatusTitle); + Check("a wrong password leaves the working copy untouched", + File.ReadAllBytes(workingCopy).SequenceEqual(oldBytes)); + Check("a wrong password keeps the pending download for a retry", + vm.PendingRemote is not null); + + core.OnOpenBytes = null; + bool retried = vm.UnlockAsync("correct").GetAwaiter().GetResult(); + Check("the retried password promotes the held download", + retried && File.ReadAllBytes(workingCopy).SequenceEqual(pendingBytes) && + vm.PendingRemote is null); + } + + private static PendingRemoteDatabase Pending(string url, string workingCopy, + byte[] bytes) => new() + { + Url = url, + Username = "user", + WorkingCopyPath = workingCopy, + Metadata = new WebDavFileInfo + { + ETag = "\"e1\"", + Size = bytes.Length, + ModifiedUnix = 42, + }, + Bytes = bytes, + }; + + private static string NewFolder(string dataDirectory, string name) + { + string folder = Path.Combine(dataDirectory, + "unlock-" + name + "-" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(folder); + return folder; + } + + private static string Sha(byte[] bytes) + => Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(bytes)) + .ToLowerInvariant(); + + private sealed class FakeText : IAppText + { + public static readonly FakeText Instance = new(); + + public string T(string english) => english; + + public string T(string format, params object?[] arguments) => + arguments.Length == 0 ? format : string.Format(format, arguments); + + public string TLong(string key, string english) => english; + } + + private sealed class FakeCoreClient : ICoreClient + { + public Task GetDatabaseInfoAsync() + => Task.FromResult(new DatabaseInfoDto()); + + public Task SetKdfAsync(string preset) + => Task.FromResult(new DatabaseInfoDto()); + + public Func? OnOpen { get; init; } + + public Func? OnOpenBytes { get; set; } + + public int OpenCalls { get; private set; } + + public int OpenBytesCalls { get; private set; } + + public byte[]? OpenedBytes { get; private set; } + + public string? OpenedPath { get; private set; } + + public string? OpenedPassword { get; private set; } + + public bool IsOpen { get; private set; } + + public string? DatabasePath { get; private set; } + + public Task OpenAsync(string path, string password) + { + OpenCalls++; + OpenedPath = path; + OpenedPassword = password; + IsOpen = true; + DatabasePath = path; + return OnOpen?.Invoke(path, password) ?? Task.CompletedTask; + } + + public Task OpenBytesAsync(byte[] kdbx, string password, string? databasePath = null) + { + OpenBytesCalls++; + OpenedBytes = kdbx; + OpenedPassword = password; + OpenedPath = databasePath; + IsOpen = true; + DatabasePath = databasePath; + return OnOpenBytes?.Invoke(kdbx, password, databasePath) ?? Task.CompletedTask; + } + + public Task LockAsync() + { + IsOpen = false; + return Task.CompletedTask; + } + + // The unlock view model only opens and locks; the sync members of the + // port are exercised by SyncCoordinatorTests with its own fake. + public Task SaveBytesAsync() + => throw new NotSupportedException(); + + public Task SaveAsync(string path, int backupRetention = 20, + Func? databaseChanged = null) + => throw new NotSupportedException(); + + public Task VerifyAsync(byte[] bytes, string password) + => throw new NotSupportedException(); + + public Task SyncDecideAsync(string remoteMetaJson, bool localDirty) + => throw new NotSupportedException(); + + public Task SyncCommitAsync(string? etag, string? sha256) + => throw new NotSupportedException(); + + public void Dispose() + { + } + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/VaultFileLockTests.cs b/tests/app-core/Keepassity.Core.Tests/VaultFileLockTests.cs new file mode 100644 index 0000000..9041c20 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/VaultFileLockTests.cs @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// The database lock has two layers: the per-account lock under the application +/// data folder and, when the vault folder is writable, a shared lock next to the +/// database so different Windows accounts or machines on a network share see +/// each other. +/// +internal static class VaultFileLockTests +{ + public static void Run(TestCheck check, string dataDirectory) + { + SharedLockIsCreatedAndRemoved(check, dataDirectory); + SharedLockHeldElsewhereBlocksOpen(check, dataDirectory); + UnwritableSharedFolderFallsBack(check, dataDirectory); + MissingDatabaseDirectoryUsesAccountLockOnly(check, dataDirectory); + } + + private static void SharedLockIsCreatedAndRemoved(TestCheck check, string dataDirectory) + { + (_, string path) = NewDatabase(dataDirectory, "shared-create"); + VaultFileLock? held = VaultFileLock.TryAcquire(path, out string? error); + check("lock: a writable vault folder also takes the shared lock", + held is not null && held.SharedLockPath is not null && + File.Exists(held.SharedLockPath), error ?? "(none)"); + check("lock: the shared lock lives under the vault folder", + held?.SharedLockPath is not null && + string.Equals(held.SharedLockPath, VaultFileLock.SharedLockPathFor(path), + StringComparison.OrdinalIgnoreCase), held?.SharedLockPath ?? "(none)"); + held?.Dispose(); + check("lock: releasing removes the shared lock file", + !File.Exists(VaultFileLock.SharedLockPathFor(path))); + } + + private static void SharedLockHeldElsewhereBlocksOpen(TestCheck check, + string dataDirectory) + { + (_, string path) = NewDatabase(dataDirectory, "shared-contended"); + string sharedPath = VaultFileLock.SharedLockPathFor(path); + Directory.CreateDirectory(Path.GetDirectoryName(sharedPath)!); + using (var otherAccount = new FileStream(sharedPath, FileMode.OpenOrCreate, + FileAccess.ReadWrite, FileShare.None)) + { + VaultFileLock? blocked = VaultFileLock.TryAcquire(path, out string? error); + check("lock: a shared lock held elsewhere refuses the open", + blocked is null && error is not null, error ?? "(none)"); + blocked?.Dispose(); + } + + VaultFileLock? acquired = VaultFileLock.TryAcquire(path, out string? afterError); + check("lock: the same vault opens after the shared lock is released", + acquired is not null, afterError ?? "(none)"); + acquired?.Dispose(); + } + + private static void UnwritableSharedFolderFallsBack(TestCheck check, + string dataDirectory) + { + (string directory, string path) = NewDatabase(dataDirectory, "shared-read-only"); + // A file where the folder should be makes the shared-lock directory + // creation fail, like a read-only or permission-restricted folder. + string blockingFile = Path.Combine(directory, ".keepassity"); + File.WriteAllBytes(blockingFile, Array.Empty()); + try + { + VaultFileLock? held = VaultFileLock.TryAcquire(path, out string? error); + check("lock: an unwritable shared folder falls back to the account lock", + held is not null && held.SharedLockPath is null, error ?? "(none)"); + VaultFileLock? second = VaultFileLock.TryAcquire(path, out string? secondError); + check("lock: the account lock still excludes a second process", + second is null && secondError is not null, secondError ?? "(none)"); + second?.Dispose(); + held?.Dispose(); + } + finally + { + File.Delete(blockingFile); + } + } + + private static void MissingDatabaseDirectoryUsesAccountLockOnly(TestCheck check, + string dataDirectory) + { + string directory = Path.Combine(dataDirectory, + "lock-missing-" + Guid.NewGuid().ToString("N")[..8]); + string path = Path.Combine(directory, "new-vault.kdbx"); + VaultFileLock? held = VaultFileLock.TryAcquire(path, out string? error); + check("lock: a not-yet-created database uses the account lock only", + held is not null && held.SharedLockPath is null, error ?? "(none)"); + held?.Dispose(); + check("lock: the account lock does not create the database directory", + !Directory.Exists(directory)); + } + + private static (string Directory, string Path) NewDatabase(string dataDirectory, + string name) + { + string directory = Path.Combine(dataDirectory, + "lock-" + name + "-" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(directory); + string path = Path.Combine(directory, "vault.kdbx"); + File.WriteAllBytes(path, new byte[] { 1, 2, 3 }); + return (directory, path); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/VaultGuardTests.cs b/tests/app-core/Keepassity.Core.Tests/VaultGuardTests.cs new file mode 100644 index 0000000..c41c734 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/VaultGuardTests.cs @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// Cross-process lock and external-change detection: a second process must not +/// be able to open the same vault, and a save must notice that another program +/// replaced the file before it overwrites it. +/// +internal static class VaultGuardTests +{ + public static void Run(TestCheck check, string rootDirectory) + { + string directory = Path.Combine(rootDirectory, "vault-guard"); + Directory.CreateDirectory(directory); + string path = Path.Combine(directory, "vault.kdbx"); + File.WriteAllBytes(path, "first-version"u8.ToArray()); + + VaultFileLock? first = VaultFileLock.TryAcquire(path, out string? firstError); + check("vault lock acquired", first is not null, firstError ?? string.Empty); + if (first is null) + { + return; + } + VaultFileLock? second = VaultFileLock.TryAcquire(path, out string? secondError); + check("second vault lock is refused", second is null, + secondError ?? string.Empty); + second?.Dispose(); + first.Dispose(); + + using (VaultFileLock? third = VaultFileLock.TryAcquire(path, out string? thirdError)) + { + check("vault lock is reusable after release", third is not null, + thirdError ?? string.Empty); + } + + VaultFingerprint original = VaultFingerprint.Capture(path); + check("fingerprint matches unchanged bytes", + original.Matches(VaultFingerprint.Capture(path))); + File.WriteAllBytes(path, "second-version"u8.ToArray()); + VaultFingerprint changed = VaultFingerprint.Capture(path); + check("fingerprint detects changed bytes", !original.Matches(changed)); + + // A metadata-only touch must not count as a content change. + File.SetLastWriteTimeUtc(path, DateTime.UtcNow.AddHours(-1)); + check("fingerprint ignores metadata-only touches", + changed.Matches(VaultFingerprint.Capture(path))); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/VaultProfileStoreTests.cs b/tests/app-core/Keepassity.Core.Tests/VaultProfileStoreTests.cs new file mode 100644 index 0000000..c45d857 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/VaultProfileStoreTests.cs @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// Headless checks for the per-vault settings file: creation from the app +/// defaults, round trip, one entry per database, and the one-time move of the +/// legacy global WebDAV source. +/// +internal static class VaultProfileStoreTests +{ + public static void Run(TestCheck check, string rootDirectory) + { + void Check(string name, bool ok, string detail = "") => check(name, ok, detail); + + string directory = Path.Combine(rootDirectory, "vaults"); + Directory.CreateDirectory(directory); + string path = Path.Combine(directory, "vaults.json"); + var defaults = new AppSettings { SyncOnSave = false, BackupRetention = 7 }; + + var store = new VaultProfileStore(path); + Check("vault profiles: empty store has no entries", store.Count == 0); + + VaultProfile first = store.Ensure("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "Keywords", defaults); + Check("vault profiles: first open inherits the app defaults", + !first.SyncOnSave && first.BackupRetention == 7, + $"{first.SyncOnSave}/{first.BackupRetention}"); + Check("vault profiles: the name is recorded", first.Name == "Keywords", first.Name ?? ""); + + VaultProfile again = store.Ensure("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "Keywords", defaults); + Check("vault profiles: reopening keeps one entry and the same profile", + store.Count == 1 && ReferenceEquals(first, again)); + Check("vault profiles: a changed name is refreshed", again.Name == "Keywords", + again.Name ?? ""); + + again.WebDavUrl = "https://dav.example.test/keepassity.kdbx"; + again.WebDavUsername = "alice"; + store.Save(); + + var reloaded = new VaultProfileStore(path); + VaultProfile? loaded = reloaded.Get("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + Check("vault profiles: the file round-trips", + loaded is not null && loaded.WebDavUrl == again.WebDavUrl && + loaded.WebDavUsername == "alice" && loaded.BackupRetention == 7, + loaded?.WebDavUrl ?? ""); + + Check("vault profiles: unknown ids return null", + reloaded.Get("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb") is null && + reloaded.Get(null) is null && reloaded.Get("") is null); + + VaultProfile second = reloaded.Ensure("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "Other", defaults); + Check("vault profiles: a second database gets its own entry", + reloaded.Count == 2 && second.Uuid.StartsWith("bbbb", StringComparison.Ordinal)); + + Check("vault profiles: removal works", reloaded.Remove(second.Uuid)); + Check("vault profiles: removal is idempotent", !reloaded.Remove(second.Uuid)); + Check("vault profiles: the count follows", reloaded.Count == 1); + + // Legacy migration: the application-wide source becomes this vault's + // source exactly once, and the old fields are cleared (no mirror). + string legacyPath = Path.Combine(directory, "vaults-legacy.json"); + var legacyStore = new VaultProfileStore(legacyPath); + var settings = new AppSettings + { + WebDavUrl = "https://dav.example.test/legacy.kdbx", + WebDavUsername = "bob", + SyncOnSave = true, + BackupRetention = 20, + }; + bool moved = VaultProfileStore.MigrateLegacySource( + settings, legacyStore, "cccccccccccccccccccccccccccccccc", "Legacy"); + VaultProfile? migrated = legacyStore.Get("cccccccccccccccccccccccccccccccc"); + Check("vault profiles: the legacy source is attached once", + moved && migrated?.WebDavUrl == "https://dav.example.test/legacy.kdbx" && + migrated.WebDavUsername == "bob", + migrated?.WebDavUrl ?? ""); + Check("vault profiles: the legacy fields are cleared", + settings.WebDavUrl is null && settings.WebDavUsername is null); + Check("vault profiles: the migration does not repeat", + !VaultProfileStore.MigrateLegacySource( + settings, legacyStore, "cccccccccccccccccccccccccccccccc", "Legacy")); + + migrated!.WebDavUrl = "https://dav.example.test/already-set.kdbx"; + settings.WebDavUrl = "https://dav.example.test/other.kdbx"; + VaultProfileStore.MigrateLegacySource( + settings, legacyStore, "cccccccccccccccccccccccccccccccc", "Legacy"); + Check("vault profiles: migration never overwrites a configured source", + legacyStore.Get("cccccccccccccccccccccccccccccccc")?.WebDavUrl == + "https://dav.example.test/already-set.kdbx", + legacyStore.Get("cccccccccccccccccccccccccccccccc")?.WebDavUrl ?? ""); + + string nestedRoot = Path.Combine(directory, "nested"); + var nested = new VaultProfileStore(Path.Combine(nestedRoot, "vaults.json")); + nested.Ensure("dddddddddddddddddddddddddddddddd", null, defaults); + nested.Save(); + Check("vault profiles: missing directories are created on save", + File.Exists(Path.Combine(nestedRoot, "vaults.json"))); + Check("vault profiles: no temporary file is left behind", + Directory.GetFiles(nestedRoot).Length == 1, + string.Join(", ", Directory.GetFiles(nestedRoot).Select(Path.GetFileName))); + + // Nothing to migrate: no source means no profile is invented. + string emptyPath = Path.Combine(directory, "vaults-empty.json"); + var emptyStore = new VaultProfileStore(emptyPath); + var noSource = new AppSettings(); + Check("vault profiles: no legacy source means no migration", + !VaultProfileStore.MigrateLegacySource(noSource, emptyStore, + "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "Nothing") && + emptyStore.Count == 0 && !File.Exists(emptyPath)); + + // The shell may know the source from the recent entry even when the + // legacy settings field was already cleared. + string overridePath = Path.Combine(directory, "vaults-override.json"); + var overrideStore = new VaultProfileStore(overridePath); + var overrideSettings = new AppSettings(); + bool attached = VaultProfileStore.MigrateLegacySource(overrideSettings, + overrideStore, "gggggggggggggggggggggggggggggggg", "FromRecent", + "https://dav.example.test/recent.kdbx", "dana"); + VaultProfile? recent = overrideStore.Get("gggggggggggggggggggggggggggggggg"); + Check("vault profiles: an explicit recent source is attached", + attached && recent?.WebDavUrl == "https://dav.example.test/recent.kdbx" && + recent.WebDavUsername == "dana", recent?.WebDavUrl ?? ""); + + // A damaged profile file must not stop the app or lose the vault itself. + string brokenPath = Path.Combine(directory, "vaults-broken.json"); + File.WriteAllText(brokenPath, "{ not json"); + var brokenStore = new VaultProfileStore(brokenPath); + Check("vault profiles: a damaged file falls back to an empty store", + brokenStore.Count == 0); + brokenStore.Ensure("ffffffffffffffffffffffffffffffff", "Recovered", defaults); + brokenStore.Save(); + Check("vault profiles: the damaged file is replaced on the next save", + new VaultProfileStore(brokenPath).Count == 1); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/VaultRecoveryTests.cs b/tests/app-core/Keepassity.Core.Tests/VaultRecoveryTests.cs new file mode 100644 index 0000000..0fef475 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/VaultRecoveryTests.cs @@ -0,0 +1,194 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// Recovery from a database that cannot be opened: the newest local backup whose +/// bytes actually decrypt must win, while unreadable, corrupt and +/// wrong-password candidates are skipped. +/// +internal static class VaultRecoveryTests +{ + private const string FixtureName = "test_db_kdbx4_with_password_aes.kdbx"; + private const string FixturePassword = "demopass"; + + public static void Run(TestCheck check, string rootDirectory) + { + NewestRestorableWins(check, rootDirectory); + CorruptNewestIsSkipped(check, rootDirectory); + EmptyNewestIsSkipped(check, rootDirectory); + ThrowingVerifierIsSkipped(check, rootDirectory); + NoBackupsReturnsNull(check, rootDirectory); + CancellationIsHonored(check, rootDirectory); + RealCorePicksTheBackupThatDecrypts(check, rootDirectory); + } + + private static void NewestRestorableWins(TestCheck check, string rootDirectory) + { + (string database, byte[] valid) = NewDamagedDatabase(rootDirectory, + "recovery-newest"); + DateTimeOffset now = DateTimeOffset.UtcNow; + BackupService.CreateBackup(database, 20, "older", now.AddMinutes(-10)); + BackupEntry newest = BackupService.CreateBackup(database, 20, "newer", now) + ?? throw new InvalidOperationException("backup was not created"); + + RestorableBackup? found = Find(database, valid).GetAwaiter().GetResult(); + check("recovery: the newest decryptable backup is chosen", + found is not null && + string.Equals(found.Entry.Path, newest.Path, StringComparison.OrdinalIgnoreCase) && + found.Bytes.SequenceEqual(valid), found?.Entry.Path ?? "(none)"); + } + + private static void CorruptNewestIsSkipped(TestCheck check, string rootDirectory) + { + (string database, byte[] valid) = NewDamagedDatabase(rootDirectory, + "recovery-corrupt"); + DateTimeOffset now = DateTimeOffset.UtcNow; + BackupEntry older = BackupService.CreateBackup(database, 20, "valid", + now.AddMinutes(-10)) ?? throw new InvalidOperationException("backup missing"); + BackupEntry newest = BackupService.CreateBackup(database, 20, "corrupt", now) + ?? throw new InvalidOperationException("backup missing"); + File.WriteAllBytes(newest.Path, + File.ReadAllBytes(TestEnvironment.Fixture("broken_random_data.kdbx"))); + + RestorableBackup? found = Find(database, valid).GetAwaiter().GetResult(); + check("recovery: a corrupt newest backup is skipped", + found is not null && + string.Equals(found.Entry.Path, older.Path, StringComparison.OrdinalIgnoreCase) && + found.Bytes.SequenceEqual(valid), found?.Entry.Path ?? "(none)"); + } + + private static void EmptyNewestIsSkipped(TestCheck check, string rootDirectory) + { + (string database, byte[] valid) = NewDamagedDatabase(rootDirectory, + "recovery-empty"); + DateTimeOffset now = DateTimeOffset.UtcNow; + BackupEntry older = BackupService.CreateBackup(database, 20, "valid", + now.AddMinutes(-10)) ?? throw new InvalidOperationException("backup missing"); + BackupEntry newest = BackupService.CreateBackup(database, 20, "empty", now) + ?? throw new InvalidOperationException("backup missing"); + File.WriteAllBytes(newest.Path, Array.Empty()); + // An unreadable candidate (open with no sharing) must be skipped too. + BackupEntry locked = BackupService.CreateBackup(database, 20, "locked", + now.AddMinutes(-5)) ?? throw new InvalidOperationException("backup missing"); + File.WriteAllBytes(locked.Path, valid); + using var exclusive = new FileStream(locked.Path, FileMode.Open, FileAccess.Read, + FileShare.None); + + RestorableBackup? found = Find(database, valid).GetAwaiter().GetResult(); + check("recovery: empty and unreadable backups are skipped", + found is not null && + string.Equals(found.Entry.Path, older.Path, StringComparison.OrdinalIgnoreCase) && + found.Bytes.SequenceEqual(valid), found?.Entry.Path ?? "(none)"); + } + + private static void ThrowingVerifierIsSkipped(TestCheck check, string rootDirectory) + { + (string database, byte[] valid) = NewDamagedDatabase(rootDirectory, + "recovery-throwing"); + DateTimeOffset now = DateTimeOffset.UtcNow; + BackupEntry older = BackupService.CreateBackup(database, 20, "valid", + now.AddMinutes(-10)) ?? throw new InvalidOperationException("backup missing"); + BackupEntry newest = BackupService.CreateBackup(database, 20, "wrong-password", now) + ?? throw new InvalidOperationException("backup missing"); + File.WriteAllBytes(newest.Path, + File.ReadAllBytes(TestEnvironment.Fixture("broken_random_data.kdbx"))); + + RestorableBackup? found = VaultRecovery.FindRestorableBackupAsync(database, bytes => + { + if (bytes.SequenceEqual(valid)) + { + return Task.FromResult(true); + } + throw new CoreException("BadPassword", "different password"); + }).GetAwaiter().GetResult(); + check("recovery: a verifier exception skips the candidate", + found is not null && + string.Equals(found.Entry.Path, older.Path, StringComparison.OrdinalIgnoreCase), + found?.Entry.Path ?? "(none)"); + } + + private static void NoBackupsReturnsNull(TestCheck check, string rootDirectory) + { + (string database, byte[] valid) = NewDamagedDatabase(rootDirectory, + "recovery-none"); + RestorableBackup? found = Find(database, valid).GetAwaiter().GetResult(); + check("recovery: no backups means no restore candidate", found is null); + } + + private static void CancellationIsHonored(TestCheck check, string rootDirectory) + { + (string database, byte[] valid) = NewDamagedDatabase(rootDirectory, + "recovery-cancel"); + _ = BackupService.CreateBackup(database, 20, "valid"); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + bool cancelled = false; + try + { + _ = VaultRecovery.FindRestorableBackupAsync(database, + _ => Task.FromResult(true), cancellation.Token).GetAwaiter().GetResult(); + } + catch (OperationCanceledException) + { + cancelled = true; + } + check("recovery: cancellation stops the search", cancelled); + } + + private static void RealCorePicksTheBackupThatDecrypts(TestCheck check, + string rootDirectory) + { + (string database, byte[] valid) = NewDamagedDatabase(rootDirectory, + "recovery-real-core"); + DateTimeOffset now = DateTimeOffset.UtcNow; + BackupEntry older = BackupService.CreateBackup(database, 20, "valid", + now.AddMinutes(-10)) ?? throw new InvalidOperationException("backup missing"); + BackupEntry newest = BackupService.CreateBackup(database, 20, "corrupt", now) + ?? throw new InvalidOperationException("backup missing"); + File.WriteAllBytes(newest.Path, + File.ReadAllBytes(TestEnvironment.Fixture("broken_random_data.kdbx"))); + if (CoreValidation.LibraryPath is null) + { + check("recovery: the real core picks the backup that decrypts", false, + "keepassity_ffi was not found; build with " + + "cargo build -p keepassity-ffi --release"); + return; + } + + Func> verifier = bytes => Task.FromResult( + CoreValidation.OpensWithPassword(bytes, FixturePassword)); + RestorableBackup? found = VaultRecovery.FindRestorableBackupAsync(database, verifier) + .GetAwaiter().GetResult(); + check("recovery: the real core picks the backup that decrypts", + found is not null && + string.Equals(found.Entry.Path, older.Path, StringComparison.OrdinalIgnoreCase) && + CoreValidation.OpensWithPassword(found.Bytes, FixturePassword), + found?.Entry.Path ?? "(none)"); + + RestorableBackup? wrongPassword = VaultRecovery.FindRestorableBackupAsync(database, + bytes => Task.FromResult( + CoreValidation.OpensWithPassword(bytes, "not-the-master-password"))) + .GetAwaiter().GetResult(); + check("recovery: a backup for another password is not offered", + wrongPassword is null); + } + + private static Task Find(string database, byte[] valid) + => VaultRecovery.FindRestorableBackupAsync(database, bytes => + Task.FromResult(bytes.SequenceEqual(valid))); + + private static (string Database, byte[] Valid) NewDamagedDatabase( + string rootDirectory, string name) + { + string directory = Path.Combine(rootDirectory, name); + Directory.CreateDirectory(directory); + string database = Path.Combine(directory, "vault.kdbx"); + byte[] valid = File.ReadAllBytes(TestEnvironment.Fixture(FixtureName)); + // Recovery only inspects the backups, so the live file may already be the + // damaged one; keeping it valid also proves recovery does not depend on it. + File.WriteAllBytes(database, valid); + return (database, valid); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/VaultSessionTests.cs b/tests/app-core/Keepassity.Core.Tests/VaultSessionTests.cs new file mode 100644 index 0000000..ae56c51 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/VaultSessionTests.cs @@ -0,0 +1,481 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// The vault session is the one place where the single-writer rules live: the +/// cross-process lock, the in-process write gate and the content fingerprint. +/// These checks pin each rule down with a fake core and real files. +/// +internal static class VaultSessionTests +{ + public static void Run(TestCheck check, string dataDirectory) + { + LockIsExclusive(check, dataDirectory); + FingerprintDetectsExternalChanges(check, dataDirectory); + SaveIsSerialized(check, dataDirectory); + SaveRefusesAnExternalChange(check, dataDirectory); + ReplaceIsDurableAndBackedUp(check, dataDirectory); + ReplaceRefusesAnExternalChange(check, dataDirectory); + RestoreBacksUpOldBytes(check, dataDirectory); + WriteTrackingDrainsBeforeExit(check, dataDirectory); + FailedSaveLeavesTheSessionUsable(check, dataDirectory); + ReadWaitsForInFlightWrite(check, dataDirectory); + ReleaseForgetsTheFingerprint(check, dataDirectory); + } + + private static void LockIsExclusive(TestCheck check, string dataDirectory) + { + (string folder, string path) = NewVault(dataDirectory, "lock", Bytes(1)); + using var first = new VaultSession(); + using var second = new VaultSession(); + check("vault session takes the lock", + first.TryAcquire(path, out string? error) && error is null && + first.DatabasePath == Path.GetFullPath(path), error ?? ""); + check("a second session cannot take the same vault", + !second.TryAcquire(path, out string? conflict) && conflict is not null, + conflict ?? ""); + check("re-acquiring the same vault keeps the lock", + first.TryAcquire(path, out _) && first.DatabasePath == Path.GetFullPath(path)); + first.Release(); + check("releasing the lock lets another session take it", + second.TryAcquire(path, out _)); + second.Release(); + check("switching vaults releases the previous lock", + first.TryAcquire(path, out _) && first.DatabasePath == Path.GetFullPath(path)); + string other = Path.Combine(folder, "other.kdbx"); + File.WriteAllBytes(other, Bytes(2)); + check("acquiring another vault moves the session", + first.TryAcquire(other, out _) && first.DatabasePath == Path.GetFullPath(other) && + second.TryAcquire(path, out _)); + second.Release(); + } + + private static void FingerprintDetectsExternalChanges(TestCheck check, string dataDirectory) + { + (_, string path) = NewVault(dataDirectory, "fingerprint", Bytes(1, 1)); + using var session = new VaultSession(); + _ = session.TryAcquire(path, out _); + session.CaptureFingerprint(); + check("unchanged file is not reported as changed", !session.ChangedOnDisk()); + File.WriteAllBytes(path, Bytes(2, 2)); + check("an external write is detected", session.ChangedOnDisk()); + session.CaptureFingerprint(); + check("capturing again accepts the new bytes", !session.ChangedOnDisk()); + File.Delete(path); + check("a deleted file is reported as changed", session.ChangedOnDisk()); + } + + private static void SaveIsSerialized(TestCheck check, string dataDirectory) + { + (_, string path) = NewVault(dataDirectory, "serialize", Bytes(1)); + using var session = new VaultSession(); + _ = session.TryAcquire(path, out _); + session.CaptureFingerprint(); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var core = new FakeCore + { + OnSave = async () => + { + entered.TrySetResult(); + await release.Task.ConfigureAwait(false); + }, + }; + Task first = session.SaveAsync(core); + entered.Task.GetAwaiter().GetResult(); + Task second = session.SaveAsync(core); + // The second save waits on the write gate: it has not reached the core. + check("a save waits for the gate instead of reaching the core", + core.SaveCalls == 1, core.SaveCalls.ToString()); + release.SetResult(); + Task.WhenAll(first, second).GetAwaiter().GetResult(); + check("both queued saves reach the core exactly once", + core.SaveCalls == 2 && core.MaxConcurrentSaves == 1, + $"calls={core.SaveCalls} max={core.MaxConcurrentSaves}"); + check("a completed save leaves the new bytes fingerprinted", + File.ReadAllBytes(path).SequenceEqual(core.ModelBytes) && + !session.ChangedOnDisk()); + } + + private static void SaveRefusesAnExternalChange(TestCheck check, string dataDirectory) + { + (_, string path) = NewVault(dataDirectory, "save-refused", Bytes(1)); + using var session = new VaultSession(); + _ = session.TryAcquire(path, out _); + session.CaptureFingerprint(); + byte[] external = Bytes(9, 9); + File.WriteAllBytes(path, external); + var core = new FakeCore(); + + CoreException? error = null; + try + { + session.SaveAsync(core).GetAwaiter().GetResult(); + } + catch (CoreException ex) + { + error = ex; + } + + check("a save refuses a file changed outside the application", + error?.Code == "VaultChanged" && core.SaveCalls == 0, + error?.Code ?? "no exception"); + check("a refused save leaves the external bytes in place", + File.ReadAllBytes(path).SequenceEqual(external)); + } + + private static void ReplaceIsDurableAndBackedUp(TestCheck check, string dataDirectory) + { + (string folder, string path) = NewVault(dataDirectory, "replace", Bytes(1, 1, 1)); + byte[] merged = Bytes(4, 5, 6); + using var session = new VaultSession(); + _ = session.TryAcquire(path, out _); + session.CaptureFingerprint(); + + session.ReplaceAsync(merged, backupRetention: 5, reason: "sync") + .GetAwaiter().GetResult(); + + check("a replacement writes the new bytes", + File.ReadAllBytes(path).SequenceEqual(merged)); + check("a replacement updates the fingerprint", !session.ChangedOnDisk()); + List backups = BackupService.ListBackups(path); + check("a replacement backs up the previous bytes", + backups.Count == 1 && + File.ReadAllBytes(backups[0].Path).SequenceEqual(Bytes(1, 1, 1)), + backups.Count.ToString()); + check("a replacement leaves no temporary file behind", + Directory.GetFiles(folder, "*keepassity-tmp*").Length == 0); + } + + private static void ReplaceRefusesAnExternalChange(TestCheck check, string dataDirectory) + { + (_, string path) = NewVault(dataDirectory, "replace-refused", Bytes(1)); + using var session = new VaultSession(); + _ = session.TryAcquire(path, out _); + session.CaptureFingerprint(); + byte[] external = Bytes(8, 8, 8); + File.WriteAllBytes(path, external); + + bool refused = false; + try + { + session.ReplaceAsync(Bytes(2, 2)).GetAwaiter().GetResult(); + } + catch (CoreException ex) when (ex.Code == "VaultChanged") + { + refused = true; + } + + check("a replacement refuses a file changed outside the application", + refused && File.ReadAllBytes(path).SequenceEqual(external)); + } + + private static void RestoreBacksUpOldBytes(TestCheck check, string dataDirectory) + { + (_, string path) = NewVault(dataDirectory, "restore", Bytes(1, 1)); + byte[] restored = Bytes(7, 7, 7); + var session = new VaultSession(); + _ = session.TryAcquire(path, out _); + session.CaptureFingerprint(); + bool restoredInsideTheGate = false; + bool fingerprintNotYetUpdatedInsideTheGate = false; + + session.RestoreAsync(restored, backupRetention: 5, afterReplace: () => + { + // The reopen callback runs inside the write gate and before the new + // fingerprint is recorded: the file already holds the restored bytes, + // and the session still expects the pre-restore content. + restoredInsideTheGate = File.ReadAllBytes(path).SequenceEqual(restored); + fingerprintNotYetUpdatedInsideTheGate = session.ChangedOnDisk(); + return Task.CompletedTask; + }).GetAwaiter().GetResult(); + + check("a restore writes the restored bytes", + File.ReadAllBytes(path).SequenceEqual(restored)); + check("the reopen callback runs after the write and before the new fingerprint", + restoredInsideTheGate && fingerprintNotYetUpdatedInsideTheGate); + check("a restore updates the fingerprint", !session.ChangedOnDisk()); + List backups = BackupService.ListBackups(path); + check("a restore backs up the previous bytes", + backups.Count == 1 && + File.ReadAllBytes(backups[0].Path).SequenceEqual(Bytes(1, 1)), + backups.Count.ToString()); + + bool rejectedEmpty = false; + try + { + session.RestoreAsync(Array.Empty()).GetAwaiter().GetResult(); + } + catch (ArgumentException) + { + rejectedEmpty = true; + } + check("a restore refuses an empty backup", rejectedEmpty); + check("a refused empty restore leaves the vault untouched", + File.ReadAllBytes(path).SequenceEqual(restored) && !session.ChangedOnDisk()); + session.Dispose(); + } + + private static void WriteTrackingDrainsBeforeExit(TestCheck check, string dataDirectory) + { + (_, string path) = NewVault(dataDirectory, "drain", Bytes(1)); + var session = new VaultSession(); + _ = session.TryAcquire(path, out _); + session.CaptureFingerprint(); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var core = new FakeCore + { + ModelBytes = Bytes(5, 5, 5), + OnSave = async () => + { + entered.TrySetResult(); + await release.Task.ConfigureAwait(false); + }, + }; + Task save = session.SaveAsync(core); + entered.Task.GetAwaiter().GetResult(); + + check("a running save is reported as in flight", session.IsWriting); + Task idle = session.WaitForIdleAsync(TimeSpan.FromSeconds(5)); + check("waiting for idle does not complete while a save runs", !idle.IsCompleted); + + bool timeoutReturned = false; + try + { + session.WaitForIdleAsync(TimeSpan.FromMilliseconds(30)).GetAwaiter().GetResult(); + timeoutReturned = true; + } + catch (OperationCanceledException) + { + timeoutReturned = false; + } + check("waiting for idle times out without throwing", + timeoutReturned && session.IsWriting); + + release.SetResult(); + save.GetAwaiter().GetResult(); + idle.GetAwaiter().GetResult(); + check("the save finishes and the session becomes idle", + !session.IsWriting && File.ReadAllBytes(path).SequenceEqual(Bytes(5, 5, 5))); + session.WaitForIdleAsync(TimeSpan.FromMilliseconds(30)).GetAwaiter().GetResult(); + check("waiting for an idle session returns immediately", !session.IsWriting); + + // Shutdown timeout: disposing the session while the writer is in flight + // must not cut the durable write short or throw from the writer. + var blocked = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var enteredAgain = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var lateCore = new FakeCore + { + ModelBytes = Bytes(6, 6), + OnSave = async () => + { + enteredAgain.TrySetResult(); + await blocked.Task.ConfigureAwait(false); + }, + }; + Task lateSave = session.SaveAsync(lateCore); + enteredAgain.Task.GetAwaiter().GetResult(); + session.Dispose(); + blocked.SetResult(); + bool writerSurvived = true; + try + { + lateSave.GetAwaiter().GetResult(); + } + catch (ObjectDisposedException) + { + writerSurvived = false; + } + check("disposing during a save lets the writer finish", + writerSurvived && File.ReadAllBytes(path).SequenceEqual(Bytes(6, 6))); + } + + private static void FailedSaveLeavesTheSessionUsable(TestCheck check, string dataDirectory) + { + (_, string path) = NewVault(dataDirectory, "save-failed", Bytes(1)); + using var session = new VaultSession(); + _ = session.TryAcquire(path, out _); + session.CaptureFingerprint(); + int calls = 0; + var core = new FakeCore + { + ModelBytes = Bytes(3, 3), + OnSave = () => + { + calls++; + if (calls == 1) + { + throw new IOException("the disk is full"); + } + return Task.CompletedTask; + }, + }; + + bool failed = false; + try + { + session.SaveAsync(core).GetAwaiter().GetResult(); + } + catch (IOException) + { + failed = true; + } + + check("a failed save reports the error instead of being silent", failed); + check("a failed save releases the write gate", !session.IsWriting); + check("the file keeps the last complete bytes after a failed save", + File.ReadAllBytes(path).SequenceEqual(Bytes(1))); + session.SaveAsync(core).GetAwaiter().GetResult(); + check("a retry after a failed save succeeds", !session.IsWriting && + File.ReadAllBytes(path).SequenceEqual(Bytes(3, 3))); + } + + private static void ReadWaitsForInFlightWrite(TestCheck check, string dataDirectory) + { + (_, string path) = NewVault(dataDirectory, "read-gate", Bytes(1)); + using var session = new VaultSession(); + _ = session.TryAcquire(path, out _); + session.CaptureFingerprint(); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var core = new FakeCore + { + ModelBytes = Bytes(8, 8, 8), + OnSave = async () => + { + entered.TrySetResult(); + await release.Task.ConfigureAwait(false); + }, + }; + Task save = session.SaveAsync(core); + entered.Task.GetAwaiter().GetResult(); + Task read = session.ReadBytesAsync(); + check("a sync read waits for the in-flight save", !read.IsCompleted); + release.SetResult(); + save.GetAwaiter().GetResult(); + byte[] bytes = read.GetAwaiter().GetResult(); + check("a sync read returns the saved bytes", + bytes.SequenceEqual(Bytes(8, 8, 8)) && !session.IsWriting); + session.WaitForIdleAsync(TimeSpan.FromMilliseconds(30)).GetAwaiter().GetResult(); + + session.Release(); + bool refused = false; + try + { + session.ReadBytesAsync().GetAwaiter().GetResult(); + } + catch (InvalidOperationException) + { + refused = true; + } + check("a released session refuses to read", refused); + } + + private static void ReleaseForgetsTheFingerprint(TestCheck check, string dataDirectory) + { + (_, string path) = NewVault(dataDirectory, "release", Bytes(1)); + using var session = new VaultSession(); + _ = session.TryAcquire(path, out _); + session.CaptureFingerprint(); + File.WriteAllBytes(path, Bytes(2)); + check("a changed vault is detected before release", session.ChangedOnDisk()); + session.Release(); + check("a released session has no database or fingerprint", + session.DatabasePath is null && !session.ChangedOnDisk()); + bool refused = false; + try + { + session.SaveAsync(new FakeCore()).GetAwaiter().GetResult(); + } + catch (InvalidOperationException) + { + refused = true; + } + check("a released session refuses to save", refused); + } + + private static (string Folder, string Path) NewVault(string dataDirectory, string name, + byte[] content) + { + string folder = Path.Combine(dataDirectory, + "vault-session-" + name + "-" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(folder); + string path = Path.Combine(folder, "vault.kdbx"); + File.WriteAllBytes(path, content); + return (folder, path); + } + + private static byte[] Bytes(params byte[] values) => values; + + private sealed class FakeCore : ICoreClient + { + public Task GetDatabaseInfoAsync() + => Task.FromResult(new DatabaseInfoDto()); + + public Task SetKdfAsync(string preset) + => Task.FromResult(new DatabaseInfoDto()); + + public byte[] ModelBytes { get; set; } = new byte[] { 4, 2, 0 }; + + public Func? OnSave { get; set; } + + public int SaveCalls { get; private set; } + + public int MaxConcurrentSaves { get; private set; } + + private int _concurrentSaves; + + public bool IsOpen => false; + + public string? DatabasePath { get; private set; } + + public async Task SaveAsync(string path, int backupRetention = 20, + Func? databaseChanged = null) + { + SaveCalls++; + _concurrentSaves++; + MaxConcurrentSaves = Math.Max(MaxConcurrentSaves, _concurrentSaves); + try + { + if (OnSave is not null) + { + await OnSave().ConfigureAwait(false); + } + if (databaseChanged?.Invoke() == true) + { + throw new CoreException("VaultChanged", "changed outside"); + } + File.WriteAllBytes(path, ModelBytes); + DatabasePath = path; + } + finally + { + _concurrentSaves--; + } + } + + public Task OpenAsync(string path, string password) => throw new NotSupportedException(); + + public Task OpenBytesAsync(byte[] kdbx, string password, string? databasePath = null) + => throw new NotSupportedException(); + + public Task LockAsync() => Task.CompletedTask; + + public Task SaveBytesAsync() => throw new NotSupportedException(); + + public Task VerifyAsync(byte[] bytes, string password) => throw new NotSupportedException(); + + public Task SyncDecideAsync(string remoteMetaJson, bool localDirty) + => throw new NotSupportedException(); + + public Task SyncCommitAsync(string? etag, string? sha256) + => throw new NotSupportedException(); + + public void Dispose() + { + } + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/VaultWriteGateTests.cs b/tests/app-core/Keepassity.Core.Tests/VaultWriteGateTests.cs new file mode 100644 index 0000000..8b6823a --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/VaultWriteGateTests.cs @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// Headless checks for the in-process vault write gate: overlapping async +/// writes must never run at the same time, and release must let the next waiter +/// proceed. +/// +internal static class VaultWriteGateTests +{ + public static void Run(TestCheck check) + { + using var gate = new VaultWriteGate(); + int active = 0; + int maxActive = 0; + var order = new List(); + Task Write(int id) => Task.Run(async () => + { + using (await gate.EnterAsync()) + { + int current = Interlocked.Increment(ref active); + maxActive = Math.Max(maxActive, current); + order.Add(id); + await Task.Delay(25); + Interlocked.Decrement(ref active); + } + }); + + Task[] tasks = { Write(1), Write(2), Write(3) }; + Task.WaitAll(tasks); + check("vault write gate serializes writers", maxActive == 1, maxActive.ToString()); + check("vault write gate runs every writer once", + order.Count == 3 && order.Distinct().Count() == 3, + string.Join(",", order)); + + bool released = false; + using (gate.EnterAsync().GetAwaiter().GetResult()) + { + released = true; + } + using (gate.EnterAsync().GetAwaiter().GetResult()) + { + check("vault write gate releases after disposal", released); + } + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/WebDavNonAsciiPathTests.cs b/tests/app-core/Keepassity.Core.Tests/WebDavNonAsciiPathTests.cs index 9947932..608b2a7 100644 --- a/tests/app-core/Keepassity.Core.Tests/WebDavNonAsciiPathTests.cs +++ b/tests/app-core/Keepassity.Core.Tests/WebDavNonAsciiPathTests.cs @@ -4,7 +4,7 @@ using System.Net.Sockets; using System.Text; using System.Xml.Linq; -using Keepassity.Mock; +using Keepassity.Core; namespace Keepassity.CoreTests; @@ -121,6 +121,12 @@ public static void Run(TestCheck check) check("webdav PUT replaced the remote content", server.ContentOf(DatabasePath).SequenceEqual(secondPayload)); + // The upload verifies what the server stored before reporting success. + request = server.TakeRequest(); + check("webdav upload reads back the stored size", + request.Method == "PROPFIND" && request.Target == DatabasePath, + request.Method + " " + request.Target); + WebDavFileInfo? refreshed = client.GetMetadataAsync().GetAwaiter().GetResult(); check("webdav metadata reflects the uploaded etag", refreshed?.ETag == "\"etag-2\"", refreshed?.ETag ?? "null"); @@ -165,6 +171,7 @@ public static void Run(TestCheck check) request.Header("If-None-Match") ?? "(missing)"); check("webdav create PUT stored the new remote file", server.ContentOf(NewDatabasePath).SequenceEqual(firstPayload)); + _ = server.TakeRequest(); // A second unconditional create must not overwrite. bool createConflict = false; @@ -248,6 +255,18 @@ public WebDavMockServer() public int Port { get; } + /// Answer the next PUT with a 303 to a readable resource. + public bool RedirectUploads { get; set; } + + /// Answer GET with a 302 to a readable resource. + public bool RedirectDownloads { get; set; } + + /// Delay every response by this much; used by the timeout checks. + public TimeSpan ResponseDelay { get; set; } = TimeSpan.Zero; + + /// When set, PUT stores only this many bytes but still answers 2xx. + public int? StoreTruncatedTo { get; set; } + public int PendingRequests { get @@ -339,6 +358,10 @@ private async Task ServeAsync(TcpClient client) { _requests.Enqueue(request); } + if (ResponseDelay > TimeSpan.Zero) + { + await Task.Delay(ResponseDelay).ConfigureAwait(false); + } Response response = Handle(request); await WriteResponseAsync(stream, response).ConfigureAwait(false); } @@ -411,7 +434,8 @@ private async Task ServeAsync(TcpClient client) } private sealed record Response(int Status, string Reason, byte[] Body, - string? ETag, DateTimeOffset? Modified, long? ContentLength = null); + string? ETag, DateTimeOffset? Modified, long? ContentLength = null, + string? Location = null); private Response Handle(WebDavRequest request) { @@ -429,11 +453,23 @@ private Response Handle(WebDavRequest request) headResource.Modified, headResource.Content.LongLength) : NotFound(); case "GET": + if (RedirectDownloads) + { + return new Response(302, "Found", Array.Empty(), null, null, + Location: "/redirected-target"); + } return _resources.TryGetValue(request.Target, out Resource? getResource) ? new Response(200, "OK", getResource.Content, getResource.ETag, getResource.Modified) : NotFound(); case "PUT": + if (RedirectUploads) + { + // A body-less GET of this target returns 200; a client + // that follows 303 would report a fake upload success. + return new Response(303, "See Other", Array.Empty(), + null, null, Location: "/redirected-target"); + } return Put(request); default: return new Response(405, "Method Not Allowed", Array.Empty(), @@ -456,7 +492,13 @@ private Response Put(WebDavRequest request) return new Response(412, "Precondition Failed", Array.Empty(), null, null); } string etag = $"\"etag-{++_etagCounter}\""; - _resources[request.Target] = new Resource(request.Body, etag, DateTimeOffset.UtcNow); + byte[] storedBody = request.Body; + if (StoreTruncatedTo is int limit && limit >= 0 && limit < storedBody.Length) + { + // Simulate a server/proxy that reports success but keeps fewer bytes. + storedBody = storedBody[..limit]; + } + _resources[request.Target] = new Resource(storedBody, etag, DateTimeOffset.UtcNow); return new Response(exists ? 200 : 201, exists ? "OK" : "Created", Array.Empty(), etag, null); } @@ -501,6 +543,10 @@ private static async Task WriteResponseAsync(NetworkStream stream, Response resp .Append(modified.ToUniversalTime().ToString("R", CultureInfo.InvariantCulture)) .Append("\r\n"); } + if (response.Location is not null) + { + headers.Append("Location: ").Append(response.Location).Append("\r\n"); + } headers.Append("Content-Type: application/octet-stream\r\n"); headers.Append("Connection: close\r\n\r\n"); await stream.WriteAsync(Encoding.ASCII.GetBytes(headers.ToString())) diff --git a/tests/app-core/Keepassity.Core.Tests/WebDavSafetyTests.cs b/tests/app-core/Keepassity.Core.Tests/WebDavSafetyTests.cs new file mode 100644 index 0000000..a3a98a6 --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/WebDavSafetyTests.cs @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Text; +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// Regressions for WebDAV transport safety: an upload redirect must never look +/// like a successful PUT, and Basic authentication must not travel over plain +/// HTTP to a non-loopback host. +/// +internal static class WebDavSafetyTests +{ + public static void Run(TestCheck check) + { + using var server = new WebDavMockServer(); + byte[] payload = Encoding.UTF8.GetBytes("database-bytes"); + DateTimeOffset modified = new(2026, 1, 2, 3, 4, 5, TimeSpan.Zero); + server.PutResource("/dav/vault.kdbx", payload, "\"etag-1\"", modified); + // A redirect target that answers 200 is exactly the shape that made a + // followed 303 report success even though the PUT never landed. + server.PutResource("/redirected-target", Encoding.UTF8.GetBytes("not-a-database"), + "\"etag-2\"", modified); + server.RedirectUploads = true; + + string url = $"http://127.0.0.1:{server.Port}/dav/vault.kdbx"; + using (var client = new WebDavClient(url, "dav-user", "dav-password")) + { + bool rejected = false; + int? status = null; + try + { + _ = client.UploadAsync(payload, "\"etag-1\"").GetAwaiter().GetResult(); + } + catch (WebDavException ex) + { + rejected = true; + status = ex.StatusCode; + } + check("webdav upload redirect is rejected", + rejected && status == 303, status?.ToString() ?? "no exception"); + check("webdav upload redirect is not followed", + server.PendingRequests == 1, + server.PendingRequests.ToString()); + } + + // A redirected GET must not carry Basic credentials to another resource + // or replace the working copy with whatever the redirect target serves. + int requestsBeforeDownload = server.PendingRequests; + server.RedirectDownloads = true; + using (var downloadClient = new WebDavClient(url, "dav-user", "dav-password")) + { + bool downloadRejected = false; + int? downloadStatus = null; + try + { + _ = downloadClient.DownloadAsync().GetAwaiter().GetResult(); + } + catch (WebDavException ex) + { + downloadRejected = true; + downloadStatus = ex.StatusCode; + } + check("webdav download redirect is rejected", + downloadRejected && downloadStatus == 302, + downloadStatus?.ToString() ?? "no exception"); + check("webdav download redirect is not followed", + server.PendingRequests == requestsBeforeDownload + 1, + (server.PendingRequests - requestsBeforeDownload).ToString()); + } + + bool nonLoopbackHttpRejected = false; + try + { + using var _ = new WebDavClient("http://example.test/vault.kdbx", "user", "password"); + } + catch (WebDavException) + { + nonLoopbackHttpRejected = true; + } + check("webdav rejects non-loopback http", nonLoopbackHttpRejected, string.Empty); + + // Loopback HTTP stays available for the in-process test harness and + // local development servers; it never carries a real remote password. + bool loopbackAccepted = false; + try + { + using var _ = new WebDavClient(url, "user", "password"); + loopbackAccepted = true; + } + catch (WebDavException) + { + loopbackAccepted = false; + } + check("webdav allows loopback http for tests", loopbackAccepted, string.Empty); + + // A server or proxy that answers 2xx but stores fewer bytes must be + // reported, not recorded as a successful upload. + using (var truncating = new WebDavMockServer()) + { + byte[] body = Encoding.UTF8.GetBytes("complete-database-bytes"); + truncating.PutResource("/dav/vault.kdbx", body, "\"etag-1\"", modified); + truncating.StoreTruncatedTo = 4; + using var client = new WebDavClient( + $"http://127.0.0.1:{truncating.Port}/dav/vault.kdbx", "user", "password"); + WebDavException? failure = null; + try + { + _ = client.UploadAsync(body, "\"etag-1\"").GetAwaiter().GetResult(); + } + catch (WebDavException ex) + { + failure = ex; + } + check("webdav upload reports a server that stored fewer bytes", + failure is not null && + failure.Message.Contains("incomplete", StringComparison.OrdinalIgnoreCase), + failure?.Message ?? "no exception"); + check("webdav truncated upload is visible in the mock store", + truncating.ContentOf("/dav/vault.kdbx").Length == 4, + truncating.ContentOf("/dav/vault.kdbx").Length.ToString()); + } + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/WebDavTimeoutTests.cs b/tests/app-core/Keepassity.Core.Tests/WebDavTimeoutTests.cs new file mode 100644 index 0000000..e1d59bb --- /dev/null +++ b/tests/app-core/Keepassity.Core.Tests/WebDavTimeoutTests.cs @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +using System.Net; +using System.Text; +using Keepassity.Core; + +namespace Keepassity.CoreTests; + +/// +/// A vault with large attachments can take minutes to download or upload on a +/// slow link; the per-request timeouts must therefore distinguish the small +/// metadata request from the whole-file transfer, and must still end a stalled +/// transfer. These checks use the loopback WebDAV server with an injected delay. +/// +internal static class WebDavTimeoutTests +{ + public static void Run(TestCheck check) + { + DefaultTimeoutsAreSizedForLargeVaults(check); + MetadataTimeoutFailsFast(check); + UploadTimeoutEndsAStalledTransfer(check); + DownloadTimeoutEndsAStalledTransfer(check); + CallerCancellationIsNotReportedAsTimeout(check); + } + + private static void DefaultTimeoutsAreSizedForLargeVaults(TestCheck check) + { + check("webdav: the metadata timeout stays short", + WebDavClient.DefaultMetadataTimeout <= TimeSpan.FromSeconds(60) && + WebDavClient.DefaultMetadataTimeout >= TimeSpan.FromSeconds(10), + WebDavClient.DefaultMetadataTimeout.ToString()); + check("webdav: the transfer timeout allows a large vault on a slow link", + WebDavClient.DefaultTransferTimeout >= TimeSpan.FromMinutes(10), + WebDavClient.DefaultTransferTimeout.ToString()); + } + + private static void MetadataTimeoutFailsFast(TestCheck check) + { + using var server = new WebDavMockServer(); + server.ResponseDelay = TimeSpan.FromMilliseconds(500); + server.PutResource("/dav/vault.kdbx", Encoding.UTF8.GetBytes("database"), + "\"etag-1\"", DateTimeOffset.UtcNow); + using var client = new WebDavClient( + $"http://127.0.0.1:{server.Port}/dav/vault.kdbx", "user", "password", + metadataTimeout: TimeSpan.FromMilliseconds(100)); + + WebDavException? failure = null; + try + { + _ = client.GetMetadataAsync().GetAwaiter().GetResult(); + } + catch (WebDavException ex) + { + failure = ex; + } + check("webdav: a slow metadata request times out with a clear error", + failure is not null && + failure.Message.Contains("timed out", StringComparison.OrdinalIgnoreCase), + failure?.Message ?? "no exception"); + } + + private static void UploadTimeoutEndsAStalledTransfer(TestCheck check) + { + using var server = new WebDavMockServer(); + server.ResponseDelay = TimeSpan.FromMilliseconds(500); + using var client = new WebDavClient( + $"http://127.0.0.1:{server.Port}/dav/vault.kdbx", "user", "password", + metadataTimeout: WebDavClient.DefaultMetadataTimeout, + transferTimeout: TimeSpan.FromMilliseconds(100)); + + WebDavException? failure = null; + try + { + _ = client.UploadAsync(Encoding.UTF8.GetBytes("payload"), ifMatch: null) + .GetAwaiter().GetResult(); + } + catch (WebDavException ex) + { + failure = ex; + } + check("webdav: a stalled upload is aborted with a clear error", + failure is not null && + failure.Message.Contains("timed out", StringComparison.OrdinalIgnoreCase), + failure?.Message ?? "no exception"); + } + + private static void DownloadTimeoutEndsAStalledTransfer(TestCheck check) + { + using var server = new WebDavMockServer(); + server.ResponseDelay = TimeSpan.FromMilliseconds(500); + server.PutResource("/dav/vault.kdbx", Encoding.UTF8.GetBytes("database"), + "\"etag-1\"", DateTimeOffset.UtcNow); + using var client = new WebDavClient( + $"http://127.0.0.1:{server.Port}/dav/vault.kdbx", "user", "password", + transferTimeout: TimeSpan.FromMilliseconds(100)); + + WebDavException? failure = null; + try + { + _ = client.DownloadAsync().GetAwaiter().GetResult(); + } + catch (WebDavException ex) + { + failure = ex; + } + check("webdav: a stalled download is aborted with a clear error", + failure is not null && + failure.Message.Contains("timed out", StringComparison.OrdinalIgnoreCase), + failure?.Message ?? "no exception"); + } + + private static void CallerCancellationIsNotReportedAsTimeout(TestCheck check) + { + using var server = new WebDavMockServer(); + server.ResponseDelay = TimeSpan.FromMilliseconds(500); + server.PutResource("/dav/vault.kdbx", Encoding.UTF8.GetBytes("database"), + "\"etag-1\"", DateTimeOffset.UtcNow); + using var client = new WebDavClient( + $"http://127.0.0.1:{server.Port}/dav/vault.kdbx", "user", "password"); + using var canceled = new CancellationTokenSource(); + canceled.Cancel(); + + bool canceledAsExpected = false; + try + { + _ = client.GetMetadataAsync(canceled.Token).GetAwaiter().GetResult(); + } + catch (OperationCanceledException) + { + canceledAsExpected = true; + } + catch (WebDavException) + { + canceledAsExpected = false; + } + check("webdav: caller cancellation is not rewritten as a timeout", + canceledAsExpected); + } +} diff --git a/tests/app-core/Keepassity.Core.Tests/WebDavTlsTests.cs b/tests/app-core/Keepassity.Core.Tests/WebDavTlsTests.cs index a06f233..2c00572 100644 --- a/tests/app-core/Keepassity.Core.Tests/WebDavTlsTests.cs +++ b/tests/app-core/Keepassity.Core.Tests/WebDavTlsTests.cs @@ -7,7 +7,7 @@ using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.Json; -using Keepassity.Mock; +using Keepassity.Core; namespace Keepassity.CoreTests; @@ -258,7 +258,7 @@ private static X509Certificate2 CreateSelfSignedCertificate() { try { - return new X509Certificate2(pfx, "keepassity", flags); + return X509CertificateLoader.LoadPkcs12(pfx, "keepassity", flags); } catch (CryptographicException) { diff --git a/tests/app-core/Keepassity.Core.Tests/packages.lock.json b/tests/app-core/Keepassity.Core.Tests/packages.lock.json index 165b79c..ce38fcb 100644 --- a/tests/app-core/Keepassity.Core.Tests/packages.lock.json +++ b/tests/app-core/Keepassity.Core.Tests/packages.lock.json @@ -1,9 +1,22 @@ { "version": 2, "dependencies": { - "net8.0": { + "net10.0": { "keepassity.core": { "type": "Project" + }, + "keepassity.viewmodels": { + "type": "Project", + "dependencies": { + "CommunityToolkit.Mvvm": "[8.4.2, )", + "Keepassity.Core": "[1.0.0, )" + } + }, + "CommunityToolkit.Mvvm": { + "type": "CentralTransitive", + "requested": "[8.4.2, )", + "resolved": "8.4.2", + "contentHash": "WadCzGEc2U+3e20avRLng4qNtt4zoOGWrdUISqJWrHe3/FSnrYjuM5Sb4yQb09LhkBXrrI4Zt3dLKgRMbItsrg==" } } } diff --git a/tests/ffi-csharp/FfiSmoke.csproj b/tests/ffi-csharp/FfiSmoke.csproj index 6fc10bc..dab6122 100644 --- a/tests/ffi-csharp/FfiSmoke.csproj +++ b/tests/ffi-csharp/FfiSmoke.csproj @@ -1,7 +1,7 @@ Exe - net8.0 + net10.0 enable enable true diff --git a/tests/ffi-csharp/packages.lock.json b/tests/ffi-csharp/packages.lock.json index dd5b66c..6afd678 100644 --- a/tests/ffi-csharp/packages.lock.json +++ b/tests/ffi-csharp/packages.lock.json @@ -1,6 +1,6 @@ { "version": 2, "dependencies": { - "net8.0": {} + "net10.0": {} } } \ No newline at end of file diff --git a/tests/fixtures/keepass-rs/.keepassity/locks/test_db_kdbx4_with_password_argon2id.kdbx.lock b/tests/fixtures/keepass-rs/.keepassity/locks/test_db_kdbx4_with_password_argon2id.kdbx.lock new file mode 100644 index 0000000..e69de29 diff --git a/tools/check-localization.ps1 b/tools/check-localization.ps1 new file mode 100644 index 0000000..615510b --- /dev/null +++ b/tools/check-localization.ps1 @@ -0,0 +1,1668 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +<# +.SYNOPSIS + Static localization gate for the Windows shell: catalogs, key usage and + placeholder parity. + +.DESCRIPTION + The Windows shell localizes by using the English source text as the catalog + key. Catalog files live in + apps/windows/Keepassity.Core/Localization/*.zh-CN.json and are embedded + resources; a key without an entry silently renders English at runtime, which + is why the mistakes this script looks for do not show up in the UI. + + Errors (always fail the run): + * every *.zh-CN.json must parse as one JSON object of non-empty string keys + and non-empty string values; a key defined by two catalog files (or twice + in one file) is a duplicate; + * every used key must have a translation: + - Loc.T("...") / Loc.TLong("...", ...) in apps/windows/**/*.cs, + - loc:LocMarkup.Text / ToolTip / Name / HelpText attributes in + apps/windows/**/*.xaml (XML entities such as & and  are + decoded), + - the string literals in the first argument of SetSyncStatus(...) and of + CommitSyncedAsync(...) (the sync status is rendered later by + SetSyncStatus, so its literal is a catalog key too), and the literals + in Report(, ...) of the sync coordinator, which forwards + the same status keys. + Adjacent C# literals ("a" + "b") are joined, and both "..." and @"..." + are decoded. A call whose first argument is not a literal (a variable, a + conditional expression, an interpolated string) cannot be resolved + statically, so it is reported as a warning instead of being checked; + two shapes are recognised instead of warned about: a variable forwarded + by the localization helpers or the sync label, and the tray's + "_unlocked ? \"locked\" : \"unlocked\"" pair (both literals are checked); + * composite format placeholders ({0}, {1}, ...) must match between a + catalog key and its translation, so a translated sentence cannot drop or + renumber an argument. + + Warnings (reported, but only fatal with -Strict): + * catalog entries that no source refers to (stale); + * translations identical to their English key (untranslated), except for + the brand/acronym allowlist below; + * C# lines that look like UI text assigned without Loc.T (candidates for + human review, not proof of a bug). Deliberately untranslated literals - + brand words, example URLs and secrets, the password/TOTP placeholder + glyphs and the tray fallback glyph - are allowlisted with their reason; + keep that list short, since anything on it is never reported again. + + Comments and string contents are lexed out before calls are located, so an + example inside a DocFX comment (Loc.cs documents Loc.T with a string) never + counts as a used key, and commented-out code never counts as an unwrapped UI + literal. + +.PARAMETER Root + Repository root to check. Defaults to the parent directory of this script, so + the script works from any working directory. + +.PARAMETER Strict + Treat warnings as errors (exit 1). Use this once the translation backlog is + empty; without it the gate can land before the work is finished. + +.PARAMETER MaxPerSection + How many lines of each error/warning category to print. Defaults to 50; the + summary always reports the full counts. + +.EXAMPLE + powershell -NoProfile -ExecutionPolicy Bypass -File tools/check-localization.ps1 + +.EXAMPLE + powershell -NoProfile -ExecutionPolicy Bypass -File tools/check-localization.ps1 -Strict + +.NOTES + Requires Windows PowerShell 5.1; uses no external modules and only reads + product files. The report is ASCII-only on purpose: Windows PowerShell 5.1 + encodes redirected stdout with the console code page, so printing raw CJK + would corrupt CI logs. Non-ASCII characters in keys are shown as \uXXXX + escapes; in quoted source lines they are replaced with "?". + Exit code 0 = pass, 1 = error (or warnings when -Strict is given). +#> +[CmdletBinding()] +param( + [string] $Root, + [switch] $Strict, + [int] $MaxPerSection = 50 +) + +$ErrorActionPreference = 'Stop' + +# ---------------------------------------------------------------- settings + +$script:Utf8NoBom = New-Object System.Text.UTF8Encoding($false) +$script:WindowsRelative = 'apps/windows' +$script:CatalogRelative = 'apps/windows/Keepassity.Core/Localization' +$script:CatalogSuffix = '.zh-cn.json' + +# Keys whose translation is legitimately identical to the English text: product +# names, acronyms and the tray tooltip state prefix (the brand is not translated; +# the state word after the dash is). +$script:UntranslatedAllowlist = @( + 'English', 'TOTP', 'WebDAV', 'KDBX', 'Keepassity', + 'Keepassity - {0}', 'Keepassity - {0} ({1})' +) + +# UI-literal review candidates that are deliberately not localized: example URLs +# and secrets in placeholders, brand words, the tray fallback glyph, password / +# TOTP placeholder glyphs, and the URL shown in a WebDAV heading. These patterns +# are matched against the line; each one carries its reason. The patterns are +# regexes anchored on the literal value: watch out for bare "?" and "." metacharacters, +# which turn an intended exact match into "anything" and silently hide candidates. +$script:UnwrappedAllowlist = @( + @{ Pattern = 'PlaceholderText\s*=\s*"https://'; Reason = 'example URL in a placeholder' }, + @{ Pattern = 'Text = "Keepassity"'; Reason = 'product name' }, + @{ Pattern = 'Title = "Keepassity"'; Reason = 'product name' }, + @{ Pattern = 'Text = "WebDAV"'; Reason = 'protocol name heading' }, + @{ Pattern = 'Text = "K"'; Reason = 'tray icon fallback glyph' }, + @{ Pattern = 'Text = "JBSWY3DPEHPK3PXP"'; Reason = 'example Base32 secret' }, + @{ Pattern = 'Text = "\?"'; Reason = 'empty TOTP placeholder' }, + @{ Pattern = 'Text = "\?\?\?\?\?\?\?\?\?\?\?\?"'; Reason = 'password mask' }, + @{ Pattern = '[\u2022\u2014]'; Reason = 'password / TOTP placeholder glyph' } +) + +# C# lexer: one pass over comments, strings and char literals. Alternation order +# matters: raw strings before plain strings, verbatim interpolated before the +# plain verbatim form, so the longest spelling wins. +$script:CSharpTokenPattern = '(?s)(?//[^\r\n]*|/\*.*?\*/)' + + '|(?"""(?:.*?)""")' + + '|(?[@$]{2}"(?:[^"]|"")*")' + + '|(?@"(?:[^"]|"")*")' + + '|(?\$"(?:[^"\\\r\n]|\\.)*")' + + '|(?"(?:[^"\\\r\n]|\\.)*")' + + '|(?''(?:[^''\\\r\n]|\\.)*'')' + +# XAML attached properties that carry a catalog key. +$script:XamlAttributePattern = @' +loc:LocMarkup\.(?Text|ToolTip|Name|HelpText)\s*=\s*(?:"(?[^"]*)"|'(?[^']*)') +'@ + +# Code that assigns or announces user-visible text. A line matching one of these, +# containing a string literal and not using Loc., is a review candidate. +$script:UiLiteralPattern = 'Text\s*=\s*"' + + '|Content\s*=\s*"' + + '|Header\s*=\s*"' + + '|PlaceholderText\s*=\s*"' + + '|ShowToast\s*\(\s*"' + + '|Title\s*=\s*"' + + '|Message\s*=\s*"' + + '|PrimaryButtonText\s*=\s*"' + + '|SecondaryButtonText\s*=\s*"' + + '|CloseButtonText\s*=\s*"' + + '|AutomationProperties\.SetName\s*\(' + + '|AutomationProperties\.SetHelpText\s*\(' + + '|new\s+MenuFlyoutItem' + +$script:RegexLocT = [regex]'(?, +# "", ...); those literals are the same keys SetSyncStatus renders. +$script:RegexReportSyncStatus = [regex]'(?[^"\\]*)"\s*:\s*"(?[^"\\]*)"' +# Unqualified T()/TLong() calls are only scanned in the Localization folder, where +# Loc.cs translates its own language-name constants; elsewhere a bare T() is not +# the catalog API. +$script:RegexBareT = [regex]'(?' + +if ($MaxPerSection -lt 1) { + $MaxPerSection = 1 +} + +# ---------------------------------------------------------------- helpers + +function Format-ReportText { + <# + Makes a string safe to print: replaces every non-ASCII and control + character with "?" (tabs become spaces), trims, and truncates. + #> + param( + [string] $Text, + [int] $MaxLength = 200 + ) + if ([string]::IsNullOrEmpty($Text)) { + return '' + } + $builder = New-Object System.Text.StringBuilder($Text.Length) + foreach ($character in $Text.ToCharArray()) { + $code = [int]$character + if ($code -eq 9) { + [void]$builder.Append(' ') + } + elseif ($code -ge 32 -and $code -le 126) { + [void]$builder.Append($character) + } + else { + [void]$builder.Append('?') + } + } + $value = $builder.ToString().Trim() + if ($value.Length -gt $MaxLength) { + if ($MaxLength -lt 8) { + return $value.Substring(0, $MaxLength) + } + return $value.Substring(0, $MaxLength - 3) + '...' + } + return $value +} + +function Format-KeyText { + <# + Like Format-ReportText but for catalog keys: non-ASCII characters become + \uXXXX escapes so the reported key is exact and the line stays ASCII. Keys + are English, but typographic punctuation (ellipsis, em dash) is common in + the source text and must not be confused with "?". + #> + param( + [string] $Text, + [int] $MaxLength = 160 + ) + if ([string]::IsNullOrEmpty($Text)) { + return '' + } + $builder = New-Object System.Text.StringBuilder + foreach ($character in $Text.ToCharArray()) { + $code = [int]$character + if ($code -eq 9) { + [void]$builder.Append(' ') + } + elseif ($code -ge 32 -and $code -le 126) { + [void]$builder.Append($character) + } + else { + [void]$builder.Append('\u' + $code.ToString('X4', [System.Globalization.CultureInfo]::InvariantCulture)) + } + } + $value = $builder.ToString().Trim() + if ($value.Length -gt $MaxLength) { + if ($MaxLength -lt 8) { + return $value.Substring(0, $MaxLength) + } + return $value.Substring(0, $MaxLength - 3) + '...' + } + return $value +} + +function Get-RelativePath { + param([string] $FullName) + $prefix = $script:RootPrefix + if ($FullName.StartsWith($prefix, [System.StringComparison]::OrdinalIgnoreCase)) { + return $FullName.Substring($prefix.Length).Replace('\', '/') + } + return $FullName.Replace('\', '/') +} + +function Read-SourceText { + param([string] $Path) + return [System.IO.File]::ReadAllText($Path, $script:Utf8NoBom) +} + +function Get-SourceFiles { + <# + Walks a directory without descending into bin/, obj/ or .git/. Recursing + through the generated build output would take seconds and only produce + generated sources. + #> + param([string] $BaseDirectory) + $files = New-Object System.Collections.Generic.List[object] + $pending = New-Object System.Collections.Generic.Stack[string] + $pending.Push($BaseDirectory) + while ($pending.Count -gt 0) { + $directory = $pending.Pop() + $children = @() + try { + $children = @(Get-ChildItem -LiteralPath $directory -ErrorAction Stop) + } + catch { + continue + } + foreach ($child in $children) { + if ($child.PSIsContainer) { + $name = $child.Name + if ($name -eq 'bin' -or $name -eq 'obj' -or $name -eq '.git') { + continue + } + $pending.Push($child.FullName) + } + else { + $files.Add($child) + } + } + } + return $files +} + +function Get-LineStarts { + <# + Offsets at which each line starts. Newlines are found with regex matches so + the scan stays fast on large files. + #> + param([string] $Text) + $starts = New-Object System.Collections.Generic.List[int] + $starts.Add(0) + foreach ($hit in [regex]::Matches($Text, "\n")) { + $starts.Add($hit.Index + 1) + } + return , $starts.ToArray() +} + +function Get-LineNumber { + param( + [int[]] $LineStarts, + [int] $Index + ) + $low = 0 + $high = $LineStarts.Length - 1 + while ($low -lt $high) { + $middle = [int][Math]::Floor(($low + $high + 1) / 2) + if ($LineStarts[$middle] -le $Index) { + $low = $middle + } + else { + $high = $middle - 1 + } + } + return $low + 1 +} + +function Get-LineText { + param( + [string] $Text, + [int[]] $LineStarts, + [int] $LineNumber, + [int] $MaxLength = 200 + ) + if ($LineNumber -lt 1 -or $LineNumber -gt $LineStarts.Length) { + return '' + } + $start = $LineStarts[$LineNumber - 1] + $end = $Text.IndexOf([char]10, $start) + if ($end -lt 0) { + $end = $Text.Length + } + $line = $Text.Substring($start, $end - $start).Trim() + return (Format-ReportText -Text $line -MaxLength $MaxLength) +} + +function Format-DynamicWarning { + <# + Builds the warning for a key position that cannot be resolved statically. + Literals that do appear in that position are remembered as referenced so a + catalog entry behind Loc.T(flag ? "locked" : "unlocked") is not called + stale, but they are never checked as keys: a fragment of an expression is + not necessarily a catalog key. + #> + param( + [string] $Relative, + [int] $Line, + $Literals, + [string] $Text, + [int[]] $LineStarts + ) + $preview = New-Object System.Collections.Generic.List[string] + $interpolated = $false + foreach ($literal in $Literals) { + if (-not $literal.Ok) { + $interpolated = $true + continue + } + if ($literal.Value.Length -eq 0) { + continue + } + [void]$script:Referenced.Add($literal.Value) + if ($preview.Count -lt 4) { + $preview.Add(('"' + (Format-KeyText -Text $literal.Value -MaxLength 80) + '"')) + } + } + $detail = Get-LineText -Text $Text -LineStarts $LineStarts -LineNumber $Line -MaxLength 160 + if ($interpolated) { + return ('[{0}] {1}:{2}: key is an interpolated string, not checked -- {3}' -f + 'dynamic', $Relative, $Line, $detail) + } + if ($preview.Count -eq 0) { + return ('[{0}] {1}:{2}: key is a variable, not checked -- {3}' -f + 'dynamic', $Relative, $Line, $detail) + } + $suffix = '' + if ($preview.Count -ge 4) { + $suffix = ', ...' + } + return ('[{0}] {1}:{2}: key expression not checked (literals: {3}{4}) -- {5}' -f + 'dynamic', $Relative, $Line, ($preview -join ', '), $suffix, $detail) +} + +function Test-UnwrappedAllowlisted { + <# + True when an unwrapped UI-literal candidate is a known intentional literal + (example URL/secret, brand, placeholder glyph). Keeps the review list focused + on strings a user could actually read in English after switching. + #> + param([string] $LineText) + foreach ($rule in $script:UnwrappedAllowlist) { + if ($LineText -match $rule.Pattern) { + return $true + } + } + return $false +} + +function New-BlankToken { + <# + Same-length blank copy of a lexed token, keeping \r and \n so line numbers + in the masked text still line up with the source. + #> + param([string] $Token) + if ($Token.IndexOf([char]10) -lt 0 -and $Token.IndexOf([char]13) -lt 0) { + return (' ' * $Token.Length) + } + return [regex]::Replace($Token, '[^\r\n]', ' ') +} + +function ConvertFrom-CSharpEscapes { + param([string] $Text) + $builder = New-Object System.Text.StringBuilder($Text.Length) + $index = 0 + $length = $Text.Length + while ($index -lt $length) { + $character = $Text[$index] + if ([int]$character -ne 92) { + [void]$builder.Append($character) + $index++ + continue + } + # backslash + $index++ + if ($index -ge $length) { + [void]$builder.Append('\') + break + } + $escape = [string]$Text[$index] + if ($escape -eq 'n') { [void]$builder.Append([char]10); $index++ } + elseif ($escape -eq 'r') { [void]$builder.Append([char]13); $index++ } + elseif ($escape -eq 't') { [void]$builder.Append([char]9); $index++ } + elseif ($escape -eq '0') { [void]$builder.Append([char]0); $index++ } + elseif ($escape -eq 'a') { [void]$builder.Append([char]7); $index++ } + elseif ($escape -eq 'b') { [void]$builder.Append([char]8); $index++ } + elseif ($escape -eq 'f') { [void]$builder.Append([char]12); $index++ } + elseif ($escape -eq 'v') { [void]$builder.Append([char]11); $index++ } + elseif ($escape -eq '"') { [void]$builder.Append('"'); $index++ } + elseif ($escape -eq '\') { [void]$builder.Append('\'); $index++ } + elseif ($escape -eq "'") { [void]$builder.Append("'"); $index++ } + elseif ($escape -eq 'u' -or $escape -eq 'U' -or $escape -eq 'x') { + $digits = 4 + if ($escape -eq 'U') { $digits = 8 } + if ($escape -eq 'x') { $digits = 4 } + $available = $length - $index - 1 + if ($available -lt 1) { + [void]$builder.Append($escape) + $index++ + continue + } + $take = [Math]::Min($digits, $available) + if ($escape -eq 'x') { + $take = 0 + while ($take -lt $digits -and ($index + 1 + $take) -lt $length) { + $candidate = [string]$Text[$index + 1 + $take] + if ($candidate -match '^[0-9A-Fa-f]$') { + $take++ + } + else { + break + } + } + if ($take -lt 1) { + [void]$builder.Append($escape) + $index++ + continue + } + } + $hex = $Text.Substring($index + 1, $take) + $codePoint = 0 + $parsed = [int]::TryParse( + $hex, + [System.Globalization.NumberStyles]::HexNumber, + [System.Globalization.CultureInfo]::InvariantCulture, + [ref] $codePoint) + if ($parsed -and $codePoint -le 0xFFFF) { + [void]$builder.Append([char]$codePoint) + $index = $index + 1 + $take + } + else { + [void]$builder.Append($escape) + $index++ + } + } + else { + [void]$builder.Append($escape) + $index++ + } + } + return $builder.ToString() +} + +function ConvertFrom-CSharpLiteral { + <# + Returns @{ Value = decoded text; Ok = $false for interpolated strings }. + #> + param( + [string] $Lexeme, + [string] $Kind + ) + if ($Kind -eq 'raw') { + $inner = $Lexeme + while ($inner.Length -gt 0 -and $inner.StartsWith('"')) { + $inner = $inner.Substring(1) + } + while ($inner.Length -gt 0 -and $inner.EndsWith('"')) { + $inner = $inner.Substring(0, $inner.Length - 1) + } + return @{ Value = $inner; Ok = $true } + } + if ($Kind -eq 'verbatim') { + if ($Lexeme.Length -lt 3) { + return @{ Value = ''; Ok = $true } + } + $inner = $Lexeme.Substring(2, $Lexeme.Length - 3) + return @{ Value = $inner.Replace('""', '"'); Ok = $true } + } + if ($Kind -eq 'regular') { + if ($Lexeme.Length -lt 2) { + return @{ Value = ''; Ok = $true } + } + $inner = $Lexeme.Substring(1, $Lexeme.Length - 2) + return @{ Value = (ConvertFrom-CSharpEscapes -Text $inner); Ok = $true } + } + # Interpolated strings are resolved at runtime; their text is not a key. + return @{ Value = ''; Ok = $false } +} + +function New-SourceScan { + <# + Returns @{ Code = ...; NoComment = ...; Literals = ... } for one C# file. + Code has comments and string/char literals blanked (identifier and block + structure survive); NoComment has only comments blanked, so per-line UI + checks still see the literals. + #> + param([string] $Text) + $tokens = [regex]::Matches($Text, $script:CSharpTokenPattern) + $code = New-Object System.Text.StringBuilder($Text.Length) + $noComment = New-Object System.Text.StringBuilder($Text.Length) + $literals = New-Object System.Collections.Generic.List[object] + $position = 0 + foreach ($token in $tokens) { + if ($token.Index -gt $position) { + $gap = $Text.Substring($position, $token.Index - $position) + [void]$code.Append($gap) + [void]$noComment.Append($gap) + } + # The lexer pattern matches exactly one alternative per token, so a group + # lookup is unnecessary: the spelling of the token identifies the kind. + # Checking it directly avoids several GroupCollection lookups per token, + # which dominates the mask build on the large window file. + $lexeme = $token.Value + $firstCode = [int]$lexeme[0] + if ($firstCode -eq 47) { + $kind = 'comment' + } + elseif ($firstCode -eq 39) { + $kind = 'chr' + } + elseif ($lexeme.Length -ge 3 -and $lexeme.StartsWith('"""')) { + $kind = 'raw' + } + elseif ($lexeme.StartsWith('@"')) { + $kind = 'verbatim' + } + elseif ($lexeme.StartsWith('$"')) { + $kind = 'interp' + } + elseif ($lexeme.StartsWith('$@') -or $lexeme.StartsWith('@$')) { + $kind = 'vinterp' + } + else { + $kind = 'regular' + } + $masked = New-BlankToken -Token $lexeme + [void]$code.Append($masked) + if ($kind -eq 'comment') { + [void]$noComment.Append($masked) + } + else { + [void]$noComment.Append($lexeme) + if ($kind -ne 'chr') { + $decoded = ConvertFrom-CSharpLiteral -Lexeme $lexeme -Kind $kind + $literals.Add([pscustomobject]@{ + Start = $token.Index + End = $token.Index + $token.Length + Kind = $kind + Value = $decoded.Value + Ok = $decoded.Ok + }) + } + } + $position = $token.Index + $token.Length + } + if ($position -lt $Text.Length) { + $gap = $Text.Substring($position) + [void]$code.Append($gap) + [void]$noComment.Append($gap) + } + return @{ + Code = $code.ToString() + NoComment = $noComment.ToString() + Literals = $literals + } +} + +function Find-CloseParen { + param( + [string] $Code, + [int] $OpenIndex + ) + $depth = 0 + $index = $OpenIndex + $length = $Code.Length + while ($index -lt $length) { + $next = $Code.IndexOfAny($script:ParenChars, $index) + if ($next -lt 0) { + return -1 + } + if ($Code[$next] -eq '(') { + $depth++ + } + else { + $depth-- + if ($depth -eq 0) { + return $next + } + } + $index = $next + 1 + } + return -1 +} + +function Get-FirstArgumentEnd { + <# + Index of the comma that ends the first argument, or the closing paren. + #> + param( + [string] $Code, + [int] $OpenIndex, + [int] $CloseIndex + ) + $depth = 0 + $index = $OpenIndex + 1 + while ($index -lt $CloseIndex) { + $character = $Code[$index] + $number = [int]$character + if ($number -eq 40 -or $number -eq 91 -or $number -eq 123) { + $depth++ + } + elseif ($number -eq 41 -or $number -eq 93 -or $number -eq 125) { + if ($depth -gt 0) { + $depth-- + } + } + elseif ($number -eq 44 -and $depth -eq 0) { + return $index + } + $index++ + } + return $CloseIndex +} + +function Get-LiteralsInRange { + <# + Literals fully inside [Start, End). The literal list is ordered by offset, + so a binary search finds the window instead of scanning every literal of a + large file once per call site. + #> + param( + $Literals, + [int] $Start, + [int] $End + ) + $found = New-Object System.Collections.Generic.List[object] + $count = $Literals.Count + $low = 0 + $high = $count - 1 + $first = $count + while ($low -le $high) { + $middle = [int][Math]::Floor(($low + $high) / 2) + if ($Literals[$middle].Start -ge $Start) { + $first = $middle + $high = $middle - 1 + } + else { + $low = $middle + 1 + } + } + for ($index = $first; $index -lt $count; $index++) { + $literal = $Literals[$index] + if ($literal.End -gt $End) { + break + } + $found.Add($literal) + } + return , $found +} + +function Get-PlaceholderSet { + <# + Composite format placeholders of a string as "{0},{2}" (or "(none)"). + {{ and }} are escapes and are ignored; alignment and format specifiers + ({0:N2}, {1,6}) contribute just their index. + #> + param([string] $Text) + # Most entries have no placeholder at all; one scan answers that immediately. + if ($Text.IndexOf('{') -lt 0) { + return '(none)' + } + $indices = New-Object System.Collections.Generic.SortedSet[int] + $index = 0 + $length = $Text.Length + while ($index -lt $length) { + $character = $Text[$index] + if ($character -eq '{') { + if (($index + 1) -lt $length -and $Text[$index + 1] -eq '{') { + $index = $index + 2 + continue + } + $close = $Text.IndexOf([char]125, $index + 1) + if ($close -lt 0) { + break + } + $inner = $Text.Substring($index + 1, $close - $index - 1) + $match = [regex]::Match($inner, '^\s*(\d+)') + if ($match.Success) { + $number = 0 + if ([int]::TryParse($match.Groups[1].Value, [ref] $number)) { + [void]$indices.Add($number) + } + } + $index = $close + 1 + continue + } + if ($character -eq '}') { + if (($index + 1) -lt $length -and $Text[$index + 1] -eq '}') { + $index = $index + 2 + continue + } + $index++ + continue + } + $index++ + } + if ($indices.Count -eq 0) { + return '(none)' + } + $parts = New-Object System.Collections.Generic.List[string] + foreach ($number in $indices) { + $parts.Add(('{' + $number + '}')) + } + return ($parts -join ',') +} + +function ConvertFrom-XmlEntity { + param([string] $Name) + if ($Name -eq 'amp') { return '&' } + if ($Name -eq 'lt') { return '<' } + if ($Name -eq 'gt') { return '>' } + if ($Name -eq 'quot') { return '"' } + if ($Name -eq 'apos') { return "'" } + if ($Name.StartsWith('#x') -or $Name.StartsWith('#X')) { + $codePoint = 0 + $parsed = [int]::TryParse( + $Name.Substring(2), + [System.Globalization.NumberStyles]::HexNumber, + [System.Globalization.CultureInfo]::InvariantCulture, + [ref] $codePoint) + if ($parsed -and $codePoint -gt 0 -and $codePoint -le 0xFFFF) { + return ([string][char]$codePoint) + } + return $null + } + if ($Name.StartsWith('#')) { + $codePoint = 0 + if ([int]::TryParse($Name.Substring(1), [ref] $codePoint) -and + $codePoint -gt 0 -and $codePoint -le 0xFFFF) { + return ([string][char]$codePoint) + } + return $null + } + return $null +} + +function Expand-XmlEntities { + param([string] $Text) + if ($Text.IndexOf('&') -lt 0) { + return $Text + } + $builder = New-Object System.Text.StringBuilder($Text.Length) + $index = 0 + while ($index -lt $Text.Length) { + $character = $Text[$index] + if ($character -eq '&') { + $semicolon = $Text.IndexOf([char]59, $index + 1) + if ($semicolon -gt $index) { + $entity = $Text.Substring($index + 1, $semicolon - $index - 1) + $decoded = ConvertFrom-XmlEntity -Name $entity + if ($null -ne $decoded) { + [void]$builder.Append($decoded) + $index = $semicolon + 1 + continue + } + } + } + [void]$builder.Append($character) + $index++ + } + return $builder.ToString() +} + +function Read-JsonString { + <# + Reads one JSON string starting at the opening quote. Returns + @{ Ok; Value; Position; Error }. + + The scan jumps from one backslash to the next with IndexOf and appends whole + runs, instead of walking character by character: catalog files are mostly + plain ASCII keys and CJK values without escapes, and Windows PowerShell 5.1 + charges a lot for a per-character loop. + #> + param( + [string] $Text, + [int] $Start + ) + if ($Start -ge $Text.Length -or $Text[$Start] -ne '"') { + return @{ Ok = $false; Value = ''; Position = $Start; Error = 'expected a quoted string' } + } + $length = $Text.Length + $index = $Start + 1 + $builder = $null + while ($index -lt $length) { + $quote = $Text.IndexOf('"', $index) + if ($quote -lt 0) { + return @{ Ok = $false; Value = ''; Position = $index; Error = 'unterminated string' } + } + $backslash = $Text.IndexOf('\', $index) + if ($backslash -lt 0 -or $backslash -gt $quote) { + $chunk = $Text.Substring($index, $quote - $index) + if ($null -eq $builder) { + return @{ Ok = $true; Value = $chunk; Position = $quote + 1; Error = '' } + } + [void]$builder.Append($chunk) + return @{ Ok = $true; Value = $builder.ToString(); Position = $quote + 1; Error = '' } + } + if ($null -eq $builder) { + $builder = New-Object System.Text.StringBuilder + } + [void]$builder.Append($Text.Substring($index, $backslash - $index)) + $index = $backslash + 1 + if ($index -ge $length) { + break + } + $escape = [string]$Text[$index] + if ($escape -eq '"') { [void]$builder.Append('"'); $index++ } + elseif ($escape -eq '\') { [void]$builder.Append('\'); $index++ } + elseif ($escape -eq '/') { [void]$builder.Append('/'); $index++ } + elseif ($escape -eq 'b') { [void]$builder.Append([char]8); $index++ } + elseif ($escape -eq 'f') { [void]$builder.Append([char]12); $index++ } + elseif ($escape -eq 'n') { [void]$builder.Append([char]10); $index++ } + elseif ($escape -eq 'r') { [void]$builder.Append([char]13); $index++ } + elseif ($escape -eq 't') { [void]$builder.Append([char]9); $index++ } + elseif ($escape -eq 'u') { + if (($index + 4) -lt $length) { + $hex = $Text.Substring($index + 1, 4) + $codePoint = 0 + $parsed = [int]::TryParse( + $hex, + [System.Globalization.NumberStyles]::HexNumber, + [System.Globalization.CultureInfo]::InvariantCulture, + [ref] $codePoint) + if (-not $parsed) { + return @{ Ok = $false; Value = ''; Position = $index; Error = 'invalid \u escape' } + } + [void]$builder.Append([char]$codePoint) + $index = $index + 5 + } + else { + return @{ Ok = $false; Value = ''; Position = $index; Error = 'truncated \u escape' } + } + } + else { + return @{ + Ok = $false + Value = '' + Position = $index + Error = ('invalid escape "\' + $escape + '"') + } + } + } + return @{ Ok = $false; Value = ''; Position = $index; Error = 'unterminated string' } +} + +function Read-CatalogEntries { + <# + Minimal reader for the catalog shape (one JSON object of string -> string). + Returns @{ Entries = list of @{ Key; Value; IsString }; Errors = list }. + It is strict on purpose: duplicate keys are valid JSON but a packaging bug, + and ConvertFrom-Json would silently keep the last value. + #> + param([string] $Text) + $entries = New-Object System.Collections.Generic.List[object] + $problems = New-Object System.Collections.Generic.List[string] + $length = $Text.Length + $position = 0 + if ($length -gt 0 -and [int]$Text[0] -eq 0xFEFF) { + $position = 1 + } + while ($position -lt $length -and [char]::IsWhiteSpace($Text[$position])) { + $position++ + } + if ($position -ge $length -or $Text[$position] -ne '{') { + $problems.Add('top-level JSON value is not an object') + return @{ Entries = $entries; Errors = $problems } + } + $position++ + while ($true) { + while ($position -lt $length -and [char]::IsWhiteSpace($Text[$position])) { + $position++ + } + if ($position -ge $length) { + $problems.Add('unexpected end of file inside the object') + break + } + if ($Text[$position] -eq '}') { + $position++ + break + } + $key = Read-JsonString -Text $Text -Start $position + if (-not $key.Ok) { + $problems.Add(('key: ' + $key.Error)) + return @{ Entries = $entries; Errors = $problems } + } + $position = $key.Position + while ($position -lt $length -and [char]::IsWhiteSpace($Text[$position])) { + $position++ + } + if ($position -ge $length -or $Text[$position] -ne ':') { + $problems.Add('expected ":" after a key') + return @{ Entries = $entries; Errors = $problems } + } + $position++ + while ($position -lt $length -and [char]::IsWhiteSpace($Text[$position])) { + $position++ + } + if ($position -ge $length) { + $problems.Add('unexpected end of file after ":"') + break + } + if ($Text[$position] -ne '"') { + $problems.Add(( + 'value for key "' + (Format-KeyText -Text $key.Value -MaxLength 120) + + '" is not a JSON string')) + return @{ Entries = $entries; Errors = $problems } + } + $value = Read-JsonString -Text $Text -Start $position + if (-not $value.Ok) { + $problems.Add(('value: ' + $value.Error)) + return @{ Entries = $entries; Errors = $problems } + } + $position = $value.Position + $entries.Add([pscustomobject]@{ + Key = $key.Value + Value = $value.Value + IsString = $true + }) + while ($position -lt $length -and [char]::IsWhiteSpace($Text[$position])) { + $position++ + } + if ($position -ge $length) { + $problems.Add('unexpected end of file inside the object') + break + } + if ($Text[$position] -eq ',') { + $position++ + continue + } + if ($Text[$position] -eq '}') { + $position++ + break + } + $problems.Add('expected "," or "}" between entries') + return @{ Entries = $entries; Errors = $problems } + } + while ($position -lt $length -and [char]::IsWhiteSpace($Text[$position])) { + $position++ + } + if ($position -lt $length) { + $problems.Add('trailing content after the top-level object') + } + return @{ Entries = $entries; Errors = $problems } +} + +function Add-UsedKey { + param( + [string] $Key, + [string] $File, + [int] $Line, + [string] $Origin + ) + if ([string]::IsNullOrEmpty($Key)) { + return + } + $location = ('{0}:{1}' -f $File, $Line) + if ($script:Used.ContainsKey($Key)) { + $entry = $script:Used[$Key] + if (-not $entry.Locations.Contains($location)) { + $entry.Locations.Add($location) + } + $entry.Count = $entry.Count + 1 + return + } + $item = [pscustomobject]@{ + Key = $Key + Locations = (New-Object System.Collections.Generic.List[string]) + Count = 1 + Origin = $Origin + } + $item.Locations.Add($location) + $script:Used[$Key] = $item +} + +function New-Warning { + param( + [string] $Tag, + [string] $Message + ) + $script:Warnings[$Tag].Add($Message) +} + +function Write-Category { + param( + [string] $Title, + $Items + ) + if ($null -eq $Items -or $Items.Count -eq 0) { + return + } + Write-Host (' {0} {1}' -f $Title, $Items.Count) + $limit = [Math]::Min($Items.Count, $MaxPerSection) + for ($index = 0; $index -lt $limit; $index++) { + Write-Host (' ' + $Items[$index]) + } + if ($Items.Count -gt $limit) { + Write-Host (' ... {0} more' -f ($Items.Count - $limit)) + } +} + +# ---------------------------------------------------------------- locate the repo + +if ([string]::IsNullOrWhiteSpace($Root)) { + $scriptRoot = $PSScriptRoot + if ([string]::IsNullOrWhiteSpace($scriptRoot)) { + $scriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path + } + $Root = Split-Path -Parent $scriptRoot +} +$Root = $Root.TrimEnd('\', '/') +if ([string]::IsNullOrWhiteSpace($Root)) { + Write-Host 'ERROR: could not determine the repository root; pass -Root .' + exit 1 +} +$script:RootPrefix = $Root + [System.IO.Path]::DirectorySeparatorChar + +$windowsRoot = Join-Path $Root $script:WindowsRelative +$catalogDirectory = Join-Path $Root $script:CatalogRelative + +if (-not (Test-Path -LiteralPath $windowsRoot)) { + Write-Host ('ERROR: {0} not found under "{1}".' -f $script:WindowsRelative, $Root) + Write-Host 'This script must live in /tools and be run from a keepassity checkout.' + exit 1 +} + +Write-Host 'keepassity localization check' +Write-Host (' repo: {0}' -f $Root.Replace('\', '/')) + +# ---------------------------------------------------------------- catalogs + +$script:Catalog = New-Object 'System.Collections.Generic.Dictionary[string,object]' ([System.StringComparer]::Ordinal) +$errorsStructural = New-Object System.Collections.Generic.List[string] +$errorsMissing = New-Object System.Collections.Generic.List[string] +$errorsPlaceholder = New-Object System.Collections.Generic.List[string] +$script:Used = New-Object 'System.Collections.Generic.Dictionary[string,object]' ([System.StringComparer]::Ordinal) +# Literals that appear in a key position but inside an expression we cannot +# resolve (Loc.T(flag ? "locked" : "unlocked")). They keep a catalog entry from +# being reported as stale, but they are not checked as keys. +$script:Referenced = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::Ordinal) +# Keys already reported as duplicates; they are not also reported as stale, which +# would be noise on top of the error. +$script:DuplicateKeys = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::Ordinal) +$script:Warnings = @{ + stale = (New-Object System.Collections.Generic.List[string]) + untranslated = (New-Object System.Collections.Generic.List[string]) + unwrapped = (New-Object System.Collections.Generic.List[string]) + dynamic = (New-Object System.Collections.Generic.List[string]) +} + +$catalogFiles = @() +if (Test-Path -LiteralPath $catalogDirectory) { + $catalogFiles = @( + Get-ChildItem -LiteralPath $catalogDirectory -File -ErrorAction Stop | + Where-Object { $_.Name.ToLowerInvariant().EndsWith($script:CatalogSuffix) } | + Sort-Object -Property Name) +} + +if ($catalogFiles.Count -eq 0) { + $errorsStructural.Add(( + '[catalog] no *{0} catalog found in {1}' -f $script:CatalogSuffix, $script:CatalogRelative)) +} + +foreach ($catalogFile in $catalogFiles) { + $relative = Get-RelativePath -FullName $catalogFile.FullName + $text = Read-SourceText -Path $catalogFile.FullName + + # The reader understands this catalog shape (one object of string -> string), + # so it produces precise messages and can see duplicate keys, which + # ConvertFrom-Json silently collapses to the last value. + $read = Read-CatalogEntries -Text $text + if ($read.Errors.Count -gt 0) { + foreach ($problem in $read.Errors) { + $errorsStructural.Add(('[{0}] {1}: {2}' -f 'json', $relative, $problem)) + } + continue + } + + # Empty keys and values are rejected first: an empty property name makes + # ConvertFrom-Json throw an opaque error instead of naming the problem. + $entryProblems = 0 + foreach ($entry in $read.Entries) { + if ([string]::IsNullOrEmpty($entry.Key)) { + $errorsStructural.Add(('[{0}] {1}: a catalog key is empty' -f 'empty-key', $relative)) + $entryProblems++ + continue + } + if ([string]::IsNullOrEmpty($entry.Value)) { + $errorsStructural.Add(( + '[empty-value] {0}: the translation of "{1}" is empty' -f + $relative, (Format-KeyText -Text $entry.Key -MaxLength 120))) + $entryProblems++ + } + } + + # Second opinion on JSON validity when nothing above already explained the + # problem; ConvertFrom-Json is strict about escapes and edge syntax. + $jsonValid = $true + if ($entryProblems -eq 0) { + try { + $parsed = ConvertFrom-Json -InputObject $text -ErrorAction Stop + if ($parsed -isnot [System.Management.Automation.PSCustomObject]) { + $errorsStructural.Add(('[{0}] {1}: top-level JSON value is not a single object' -f 'json', $relative)) + $jsonValid = $false + } + } + catch { + $errorsStructural.Add(( + '[json] {0}: {1}' -f $relative, (Format-ReportText -Text $_.Exception.Message))) + $jsonValid = $false + } + } + if (-not $jsonValid) { + continue + } + + foreach ($entry in $read.Entries) { + if ([string]::IsNullOrEmpty($entry.Key) -or [string]::IsNullOrEmpty($entry.Value)) { + continue + } + if ($script:Catalog.ContainsKey($entry.Key)) { + $existing = $script:Catalog[$entry.Key] + [void]$script:DuplicateKeys.Add($entry.Key) + $errorsStructural.Add(( + '[duplicate] "{0}" is defined in {1} and {2}' -f + (Format-KeyText -Text $entry.Key -MaxLength 120), $existing.File, $relative)) + continue + } + $script:Catalog[$entry.Key] = [pscustomobject]@{ + Key = $entry.Key + Value = $entry.Value + File = $relative + } + } +} + +# ---------------------------------------------------------------- sources + +$sourceFiles = @(Get-SourceFiles -BaseDirectory $windowsRoot) +$csFiles = @($sourceFiles | Where-Object { $_.Extension -eq '.cs' } | Sort-Object -Property FullName) +$xamlFiles = @($sourceFiles | Where-Object { $_.Extension -eq '.xaml' } | Sort-Object -Property FullName) + +$countLocT = 0 +$countLocTLong = 0 +$countInternalT = 0 +$countXaml = 0 +$countSync = 0 + +foreach ($file in $csFiles) { + $relative = Get-RelativePath -FullName $file.FullName + $text = Read-SourceText -Path $file.FullName + $scan = New-SourceScan -Text $text + $code = $scan.Code + $lineStarts = Get-LineStarts -Text $text + $inLocalizationFolder = $relative.Contains('/Localization/') + + # ---- Loc.T: the first argument carries the catalog key. + foreach ($hit in $script:RegexLocT.Matches($code)) { + $line = Get-LineNumber -LineStarts $lineStarts -Index $hit.Index + $openIndex = $hit.Index + $hit.Length - 1 + $closeIndex = Find-CloseParen -Code $code -OpenIndex $openIndex + if ($closeIndex -lt 0) { + New-Warning 'dynamic' ('[{0}] {1}:{2}: Loc.T( call is not closed on this line' -f 'dynamic', $relative, $line) + continue + } + $argumentEnd = Get-FirstArgumentEnd -Code $code -OpenIndex $openIndex -CloseIndex $closeIndex + $argumentCode = $code.Substring($openIndex + 1, $argumentEnd - $openIndex - 1) + $remainder = ($argumentCode -replace '\s', '').Replace('+', '') + $siteLiterals = Get-LiteralsInRange -Literals $scan.Literals -Start ($openIndex + 1) -End $argumentEnd + if ($remainder.Length -eq 0 -and $siteLiterals.Count -gt 0) { + $resolved = $true + $parts = New-Object System.Collections.Generic.List[string] + foreach ($literal in $siteLiterals) { + if (-not $literal.Ok) { + $resolved = $false + break + } + $parts.Add($literal.Value) + } + if (-not $resolved) { + New-Warning 'dynamic' (Format-DynamicWarning -Relative $relative -Line $line ` + -Literals $siteLiterals -Text $text -LineStarts $lineStarts) + continue + } + $key = ($parts -join '') + if ($key.Length -eq 0) { + New-Warning 'dynamic' ('[{0}] {1}:{2}: Loc.T("") has an empty key' -f 'dynamic', $relative, $line) + continue + } + Add-UsedKey -Key $key -File $relative -Line $line -Origin 'Loc.T' + $countLocT++ + continue + } + # Loc.cs/LocMarkup.cs intentionally forward a variable key (the attached + # properties call Loc.T with the element's registered key), and the sync + # label forwards its stored source string; neither is a missing key. + if ($inLocalizationFolder -or $argumentCode -match '_syncStatusSource') { + continue + } + $lineText = Get-LineText -Text $text -LineStarts $lineStarts -LineNumber $line -MaxLength 400 + $conditional = $script:RegexConditionalKey.Match($lineText) + if ($conditional.Success) { + Add-UsedKey -Key $conditional.Groups['yes'].Value -File $relative -Line $line -Origin 'Loc.T' + Add-UsedKey -Key $conditional.Groups['no'].Value -File $relative -Line $line -Origin 'Loc.T' + $countLocT += 2 + continue + } + New-Warning 'dynamic' (Format-DynamicWarning -Relative $relative -Line $line ` + -Literals $siteLiterals -Text $text -LineStarts $lineStarts) + } + + # ---- Loc.TLong: the first argument is a symbolic key. + foreach ($hit in $script:RegexLocTLong.Matches($code)) { + $line = Get-LineNumber -LineStarts $lineStarts -Index $hit.Index + $openIndex = $hit.Index + $hit.Length - 1 + $closeIndex = Find-CloseParen -Code $code -OpenIndex $openIndex + if ($closeIndex -lt 0) { + New-Warning 'dynamic' ('[{0}] {1}:{2}: Loc.TLong( call is not closed on this line' -f 'dynamic', $relative, $line) + continue + } + $argumentEnd = Get-FirstArgumentEnd -Code $code -OpenIndex $openIndex -CloseIndex $closeIndex + $argumentCode = $code.Substring($openIndex + 1, $argumentEnd - $openIndex - 1) + $remainder = ($argumentCode -replace '\s', '').Replace('+', '') + $siteLiterals = Get-LiteralsInRange -Literals $scan.Literals -Start ($openIndex + 1) -End $argumentEnd + if ($remainder.Length -eq 0 -and $siteLiterals.Count -gt 0) { + $resolved = $true + $key = '' + foreach ($literal in $siteLiterals) { + if (-not $literal.Ok) { + $resolved = $false + break + } + $key = $key + $literal.Value + } + if (-not $resolved) { + New-Warning 'dynamic' (Format-DynamicWarning -Relative $relative -Line $line ` + -Literals $siteLiterals -Text $text -LineStarts $lineStarts) + continue + } + if ($key.Length -eq 0) { + New-Warning 'dynamic' ('[{0}] {1}:{2}: Loc.TLong("", ...) has an empty key' -f 'dynamic', $relative, $line) + continue + } + Add-UsedKey -Key $key -File $relative -Line $line -Origin 'Loc.TLong' + $countLocTLong++ + continue + } + # Loc.cs/LocMarkup.cs/LocText.cs intentionally forward a variable key + # (the shell's view-model text adapter and the XAML attached properties + # pass a key that was registered by the caller); that is not a missing key. + if ($inLocalizationFolder) { + continue + } + New-Warning 'dynamic' (Format-DynamicWarning -Relative $relative -Line $line ` + -Literals $siteLiterals -Text $text -LineStarts $lineStarts) + } + + # ---- SetSyncStatus: every literal in the first argument is a catalog key. + # The status method stores its source string and renders it later, so the + # literals can be a direct string, a conditional expression, or nothing at + # all (a variable passed through from another code path). + foreach ($hit in $script:RegexSetSyncStatus.Matches($code)) { + $openIndex = $hit.Index + $hit.Length - 1 + $closeIndex = Find-CloseParen -Code $code -OpenIndex $openIndex + if ($closeIndex -lt 0) { + continue + } + $line = Get-LineNumber -LineStarts $lineStarts -Index $hit.Index + $argumentEnd = Get-FirstArgumentEnd -Code $code -OpenIndex $openIndex -CloseIndex $closeIndex + $argumentCode = $code.Substring($openIndex + 1, $argumentEnd - $openIndex - 1) + if ($argumentCode -match 'Loc\.') { + # Wrapped in Loc.T already; that call site was handled above. + continue + } + $siteLiterals = Get-LiteralsInRange -Literals $scan.Literals -Start ($openIndex + 1) -End $argumentEnd + foreach ($literal in $siteLiterals) { + if (-not $literal.Ok) { + New-Warning 'dynamic' ('[{0}] {1}:{2}: interpolated string as the sync status: {3}' -f + 'dynamic', $relative, $line, (Get-LineText -Text $text -LineStarts $lineStarts -LineNumber $line)) + continue + } + if ($literal.Value.Length -eq 0) { + continue + } + Add-UsedKey -Key $literal.Value -File $relative -Line $line -Origin 'SetSyncStatus' + $countSync++ + } + } + + # ---- CommitSyncedAsync: its status argument is a catalog key, rendered by + # SetSyncStatus(status) later. Only literals inside the call are keys (the + # other arguments are values/variables). + foreach ($hit in $script:RegexCommitSynced.Matches($code)) { + $openIndex = $hit.Index + $hit.Length - 1 + $closeIndex = Find-CloseParen -Code $code -OpenIndex $openIndex + if ($closeIndex -lt 0) { + continue + } + $line = Get-LineNumber -LineStarts $lineStarts -Index $hit.Index + $siteLiterals = Get-LiteralsInRange -Literals $scan.Literals ` + -Start ($openIndex + 1) -End $closeIndex + foreach ($literal in $siteLiterals) { + if (-not $literal.Ok -or $literal.Value.Length -eq 0) { + continue + } + Add-UsedKey -Key $literal.Value -File $relative -Line $line ` + -Origin 'CommitSyncedAsync' + $countSync++ + } + } + + # ---- Report(, "", ...): the sync coordinator's status + # lines, rendered by the shell's SetSyncStatus. The status port is the first + # argument, so the key literals follow it; a forwarded variable has no + # literal and is checked where the literal is written. + foreach ($hit in $script:RegexReportSyncStatus.Matches($code)) { + $parenIndex = $code.IndexOf('(', $hit.Index) + if ($parenIndex -lt 0) { + continue + } + $closeIndex = Find-CloseParen -Code $code -OpenIndex $parenIndex + if ($closeIndex -lt 0) { + continue + } + $line = Get-LineNumber -LineStarts $lineStarts -Index $hit.Index + $siteLiterals = Get-LiteralsInRange -Literals $scan.Literals ` + -Start $hit.Index -End $closeIndex + foreach ($literal in $siteLiterals) { + if (-not $literal.Ok -or $literal.Value.Length -eq 0) { + continue + } + Add-UsedKey -Key $literal.Value -File $relative -Line $line -Origin 'Report' + $countSync++ + } + } + + # ---- Bare T()/TLong() inside the Localization folder (Loc.cs translates its + # own language-name constants). Elsewhere a bare T() is not the catalog API. + if ($inLocalizationFolder) { + foreach ($hit in $script:RegexBareT.Matches($code)) { + $openIndex = $hit.Index + $hit.Length - 1 + $closeIndex = Find-CloseParen -Code $code -OpenIndex $openIndex + if ($closeIndex -lt 0) { + continue + } + $argumentEnd = Get-FirstArgumentEnd -Code $code -OpenIndex $openIndex -CloseIndex $closeIndex + $argumentCode = $code.Substring($openIndex + 1, $argumentEnd - $openIndex - 1) + $remainder = ($argumentCode -replace '\s', '').Replace('+', '') + if ($remainder.Length -ne 0) { + # Declarations (T(string english)) and variable lookups are not keys. + continue + } + $siteLiterals = Get-LiteralsInRange -Literals $scan.Literals -Start ($openIndex + 1) -End $argumentEnd + if ($siteLiterals.Count -eq 0) { + continue + } + $resolved = $true + $parts = New-Object System.Collections.Generic.List[string] + foreach ($literal in $siteLiterals) { + if (-not $literal.Ok) { + $resolved = $false + break + } + $parts.Add($literal.Value) + } + if (-not $resolved) { + continue + } + $key = ($parts -join '') + if ($key.Length -eq 0) { + continue + } + $line = Get-LineNumber -LineStarts $lineStarts -Index $hit.Index + Add-UsedKey -Key $key -File $relative -Line $line -Origin 'T' + $countInternalT++ + } + } + + # ---- Unwrapped UI literals: review candidates, not failures. The UI pattern + # is matched once over the whole file (a single regex pass instead of one per + # line) and the matching lines are then filtered with cheap ordinal checks. + $noCommentLines = $scan.NoComment -split "\r?\n" + $candidateLines = New-Object System.Collections.Generic.SortedSet[int] + foreach ($patternHit in [regex]::Matches($scan.NoComment, $script:UiLiteralPattern)) { + $lineNumber = Get-LineNumber -LineStarts $lineStarts -Index $patternHit.Index + [void]$candidateLines.Add($lineNumber) + } + foreach ($lineNumber in $candidateLines) { + $lineText = $noCommentLines[$lineNumber - 1] + if ($lineText.IndexOf('"') -lt 0 -or + $lineText.IndexOf('Loc.') -ge 0 -or + $lineText.IndexOf('AppLog.') -ge 0 -or + $lineText.IndexOf('[DllImport') -ge 0 -or + $lineText.IndexOf('JsonPropertyName') -ge 0) { + continue + } + if (Test-UnwrappedAllowlisted -LineText $lineText) { + continue + } + $display = Format-ReportText -Text $lineText.Trim() -MaxLength 180 + New-Warning 'unwrapped' ('[{0}] {1}:{2}: {3}' -f 'unwrapped', $relative, $lineNumber, $display) + } +} + +# ---- XAML attached properties. +foreach ($file in $xamlFiles) { + $relative = Get-RelativePath -FullName $file.FullName + $text = Read-SourceText -Path $file.FullName + $lineStarts = Get-LineStarts -Text $text + # Comments are blanked in place so offsets (and therefore line numbers) hold. + $masked = $text + $comments = $script:XmlCommentPattern.Matches($text) + if ($comments.Count -gt 0) { + $builder = New-Object System.Text.StringBuilder($text.Length) + $position = 0 + foreach ($comment in $comments) { + if ($comment.Index -gt $position) { + [void]$builder.Append($text.Substring($position, $comment.Index - $position)) + } + [void]$builder.Append((New-BlankToken -Token $comment.Value)) + $position = $comment.Index + $comment.Length + } + if ($position -lt $text.Length) { + [void]$builder.Append($text.Substring($position)) + } + $masked = $builder.ToString() + } + $pattern = [regex]$script:XamlAttributePattern + foreach ($hit in $pattern.Matches($masked)) { + $line = Get-LineNumber -LineStarts $lineStarts -Index $hit.Index + $value = '' + if ($hit.Groups['dq'].Success) { + $value = $hit.Groups['dq'].Value + } + else { + $value = $hit.Groups['sq'].Value + } + if ($value.StartsWith('{}')) { + $value = $value.Substring(2) + } + elseif ($value.StartsWith('{')) { + New-Warning 'dynamic' ('[{0}] {1}:{2}: markup extension in loc:{3}, not checked' -f + 'dynamic', $relative, $line, $hit.Groups['prop'].Value) + continue + } + $decoded = Expand-XmlEntities -Text $value + if ($decoded.Length -eq 0) { + New-Warning 'dynamic' ('[{0}] {1}:{2}: empty loc:{3} value' -f + 'dynamic', $relative, $line, $hit.Groups['prop'].Value) + continue + } + Add-UsedKey -Key $decoded -File $relative -Line $line -Origin 'XAML' + $countXaml++ + } +} + +# ---------------------------------------------------------------- checks + +$catalogKeys = New-Object System.Collections.Generic.List[string] +foreach ($key in $script:Catalog.Keys) { + $catalogKeys.Add($key) +} +$catalogKeys.Sort([System.StringComparer]::Ordinal) + +# Placeholder parity and untranslated entries, in catalog order. +foreach ($key in $catalogKeys) { + $entry = $script:Catalog[$key] + $keyPlaceholders = Get-PlaceholderSet -Text $key + $translationPlaceholders = Get-PlaceholderSet -Text $entry.Value + if ($keyPlaceholders -ne $translationPlaceholders) { + $errorsPlaceholder.Add(( + '[placeholder] "{0}" ({1}): key placeholders {2} but translation placeholders {3}' -f + (Format-KeyText -Text $key -MaxLength 140), $entry.File, + $keyPlaceholders, $translationPlaceholders)) + } + if ($entry.Value -ceq $key) { + $allowed = $false + foreach ($allowlisted in $script:UntranslatedAllowlist) { + if ($allowlisted -ceq $key) { + $allowed = $true + break + } + } + if (-not $allowed) { + New-Warning 'untranslated' ('[{0}] "{1}" ({2}): translation is identical to the English key' -f + 'untranslated', (Format-KeyText -Text $key -MaxLength 140), $entry.File) + } + } + # Product-name convention: UI text spells the product "Keepassity"; the + # lowercase form is reserved for file/folder names, environment variables, + # identifiers and URLs. Catalog keys and values are UI text. + if ($key -cmatch 'keepassity') { + $errorsStructural.Add(( + '[naming] "{0}" ({1}): lowercase product name in a UI catalog key; use "Keepassity"' -f + (Format-KeyText -Text $key -MaxLength 160), $entry.File)) + } + if ($entry.Value -cmatch 'keepassity') { + $errorsStructural.Add(( + '[naming] translation of "{0}" ({1}): lowercase product name in UI text; use "Keepassity"' -f + (Format-KeyText -Text $key -MaxLength 160), $entry.File)) + } +} + +# Used keys without a translation, and catalog entries nobody uses. +$usedKeys = New-Object System.Collections.Generic.List[string] +foreach ($key in $script:Used.Keys) { + $usedKeys.Add($key) +} +$usedKeys.Sort([System.StringComparer]::Ordinal) + +foreach ($key in $usedKeys) { + if ($script:Catalog.ContainsKey($key)) { + continue + } + $entry = $script:Used[$key] + $suffix = '' + if ($entry.Locations.Count -gt 1) { + $suffix = (' (and {0} more site(s))' -f ($entry.Locations.Count - 1)) + } + $errorsMissing.Add(( + '[missing] {0}: no zh-CN translation for "{1}"{2}' -f + $entry.Locations[0], (Format-KeyText -Text $key -MaxLength 160), $suffix)) +} + +foreach ($key in $catalogKeys) { + if ($script:Used.ContainsKey($key) -or $script:Referenced.Contains($key)) { + continue + } + if ($script:DuplicateKeys.Contains($key)) { + continue + } + $entry = $script:Catalog[$key] + New-Warning 'stale' ('[{0}] "{1}" ({2}): no source reference' -f + 'stale', (Format-KeyText -Text $key -MaxLength 140), $entry.File) +} + +# ---------------------------------------------------------------- report + +Write-Host (' catalogs: {0} file(s), {1} entries' -f $catalogFiles.Count, $script:Catalog.Count) +Write-Host (' sources : {0} .cs, {1} .xaml' -f $csFiles.Count, $xamlFiles.Count) +Write-Host (' usage : {0} Loc.T, {1} Loc.TLong, {2} T() in Localization, {3} XAML attribute(s), {4} sync-status literal(s)' -f + $countLocT, $countLocTLong, $countInternalT, $countXaml, $countSync) +Write-Host '' + +$errorLists = @( + @{ Title = 'structural'; Items = $errorsStructural }, + @{ Title = 'missing'; Items = $errorsMissing }, + @{ Title = 'placeholder'; Items = $errorsPlaceholder } +) +$errorCount = $errorsStructural.Count + $errorsMissing.Count + $errorsPlaceholder.Count + +if ($errorCount -eq 0) { + Write-Host 'ERRORS: none' +} +else { + Write-Host ('ERRORS ({0})' -f $errorCount) + foreach ($group in $errorLists) { + if ($group.Items.Count -eq 0) { + continue + } + $limit = [Math]::Min($group.Items.Count, $MaxPerSection) + for ($index = 0; $index -lt $limit; $index++) { + Write-Host (' ' + $group.Items[$index]) + } + if ($group.Items.Count -gt $limit) { + Write-Host (' ... {0} more {1} error(s)' -f ($group.Items.Count - $limit), $group.Title) + } + } +} + +$warningOrder = @('stale', 'untranslated', 'unwrapped', 'dynamic') +$warningCount = 0 +foreach ($tag in $warningOrder) { + $warningCount = $warningCount + $script:Warnings[$tag].Count +} + +Write-Host '' +if ($warningCount -eq 0) { + Write-Host 'WARNINGS: none' +} +else { + Write-Host ('WARNINGS ({0})' -f $warningCount) + foreach ($tag in $warningOrder) { + Write-Category -Title $tag -Items $script:Warnings[$tag] + } +} + +Write-Host '' +Write-Host ('summary: {0} error(s), {1} warning(s)' -f $errorCount, $warningCount) +if ($errorCount -gt 0) { + Write-Host 'RESULT: FAIL' + exit 1 +} +if ($Strict -and $warningCount -gt 0) { + Write-Host 'RESULT: FAIL (-Strict treats warnings as errors)' + exit 1 +} +if ($warningCount -gt 0) { + Write-Host 'RESULT: PASS (warnings only; rerun with -Strict to fail on them)' +} +else { + Write-Host 'RESULT: PASS' +} +exit 0 diff --git a/tools/check-ui-strings.ps1 b/tools/check-ui-strings.ps1 index 02b320e..f2e4d8b 100644 --- a/tools/check-ui-strings.ps1 +++ b/tools/check-ui-strings.ps1 @@ -4,9 +4,10 @@ Fail when hard-coded CJK text appears in the Windows shell sources. .DESCRIPTION - The Windows UI is English-only (see docs/testing.md). This check scans - apps/windows/**/*.cs and apps/windows/**/*.xaml for CJK characters and fails - with "file:line" for every hit. + UI text lives in the embedded language catalogs, not in the WinUI sources (see + docs/testing.md). This check scans apps/windows/**/*.cs and *.xaml for hard-coded + CJK characters and fails with "file:line" for every hit, so a translation can + never bypass the catalogs or drift from them. Two lines in MainWindow.xaml.cs are allowed: they are the data-matching predicates for the localized KeePass group names of the recycle-bin and @@ -52,10 +53,12 @@ $cjkPattern = '[\u3000-\u303F\u3040-\u30FF\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAF # Allowed lines, as Unicode code points: # recycle bin: U+56DE U+6536 U+7AD9 # templates: U+6A21 U+677F +# The two predicates moved to MainWindow.Navigation.cs when the shell was split +# into partial files; the allowlist follows the file that holds them now. $recycleBin = [string][char]0x56DE + [char]0x6536 + [char]0x7AD9 $templates = [string][char]0x6A21 + [char]0x677F $allowedLines = @{} -$allowedLines['apps/windows/Keepassity.Mock/MainWindow.xaml.cs'] = @( +$allowedLines['apps/windows/Keepassity.App/MainWindow.Navigation.cs'] = @( ('return value.Equals("' + $recycleBin + '", StringComparison.OrdinalIgnoreCase) ||'), ('return value.Equals("' + $templates + '", StringComparison.OrdinalIgnoreCase) ||') ) @@ -105,12 +108,13 @@ foreach ($file in $files) { } if ($violations.Count -gt 0) { - Write-Host "FAIL: $($violations.Count) hard-coded CJK line(s) in the English UI sources:" + Write-Host "FAIL: $($violations.Count) hard-coded CJK line(s) in the shell sources:" foreach ($violation in $violations) { Write-Host " $violation" } - Write-Host 'Only the documented data-matching literals in MainWindow.xaml.cs are allowed;' - Write-Host 'see docs/testing.md (UI strings).' + Write-Host 'Add the translation to the language catalog and reference the English key instead;' + Write-Host 'only the documented data-matching literals in MainWindow.Navigation.cs are allowed.' + Write-Host 'See docs/testing.md (UI strings).' exit 1 } diff --git a/tools/drills/README.md b/tools/drills/README.md index bfb5405..c1bdb2a 100644 --- a/tools/drills/README.md +++ b/tools/drills/README.md @@ -10,8 +10,8 @@ master password `demopass`). Never point these scripts at a real vault. ## Prerequisites -- Windows with **.NET SDK 8 or newer** (both projects target `net8.0`) and the - matching .NET 8 runtime. +- Windows with **.NET SDK 10 or newer** (both projects target `net10.0`) and the + matching .NET 10 runtime. - **Rust/cargo** for the native core; run commands from the repository root. - The synthetic fixture `tests/fixtures/synthetic/synthetic-500.kdbx` (committed; regenerate with `tools/fixture-gen/regenerate.ps1` if needed). @@ -29,7 +29,7 @@ powershell -NoProfile -ExecutionPolicy Bypass -File tools\drills\build-drills.ps ``` This builds `mock-webdav`, `runner` (Release), builds `keepassity-ffi` in release -and copies the FFI DLL into `tools\drills\runner\bin\Release\net8.0\`. Every drill +and copies the FFI DLL into `tools\drills\runner\bin\Release\net10.0\`. Every drill script calls the same initialisation, so running this first is optional (useful for CI or to check the build in isolation). Equivalent manual steps: diff --git a/tools/drills/_common.ps1 b/tools/drills/_common.ps1 index 4d74242..89973b5 100644 --- a/tools/drills/_common.ps1 +++ b/tools/drills/_common.ps1 @@ -16,8 +16,8 @@ function Initialize-Drills { $repoRoot = $script:DrillRepoRoot $mockProject = Join-Path $repoRoot 'tools/drills/mock-webdav/MockWebDav.csproj' $runnerProject = Join-Path $repoRoot 'tools/drills/runner/DrillRunner.csproj' - $runnerBin = Join-Path $repoRoot 'tools/drills/runner/bin/Release/net8.0' - $mockBin = Join-Path $repoRoot 'tools/drills/mock-webdav/bin/Release/net8.0' + $runnerBin = Join-Path $repoRoot 'tools/drills/runner/bin/Release/net10.0' + $mockBin = Join-Path $repoRoot 'tools/drills/mock-webdav/bin/Release/net10.0' $fixture = Join-Path $repoRoot 'tests/fixtures/synthetic/synthetic-500.kdbx' if (-not (Test-Path -LiteralPath $fixture)) { diff --git a/tools/drills/mock-webdav/MockWebDav.csproj b/tools/drills/mock-webdav/MockWebDav.csproj index 413dccb..f1e7355 100644 --- a/tools/drills/mock-webdav/MockWebDav.csproj +++ b/tools/drills/mock-webdav/MockWebDav.csproj @@ -4,7 +4,7 @@ .NET SDK is installed. --> Exe - net8.0 + net10.0 enable enable MockWebDav diff --git a/tools/drills/runner/DrillRunner.csproj b/tools/drills/runner/DrillRunner.csproj index 86de5e5..98f0331 100644 --- a/tools/drills/runner/DrillRunner.csproj +++ b/tools/drills/runner/DrillRunner.csproj @@ -5,7 +5,7 @@ run headless. --> Exe - net8.0 + net10.0 enable enable DrillRunner diff --git a/tools/drills/runner/Drills.cs b/tools/drills/runner/Drills.cs index 874511d..ce94703 100644 --- a/tools/drills/runner/Drills.cs +++ b/tools/drills/runner/Drills.cs @@ -5,7 +5,7 @@ using System.Net; using System.Text; using System.Text.Json; -using Keepassity.Mock; +using Keepassity.Core; namespace Keepassity.Drills.Runner; diff --git a/tools/drills/runner/Program.cs b/tools/drills/runner/Program.cs index 67792bc..d14f9b7 100644 --- a/tools/drills/runner/Program.cs +++ b/tools/drills/runner/Program.cs @@ -17,7 +17,7 @@ using System.Security.Cryptography; using System.Text.Json; -using Keepassity.Mock; +using Keepassity.Core; namespace Keepassity.Drills.Runner; diff --git a/tools/icon/make-app-icon.py b/tools/icon/make-app-icon.py index 7696918..a89060c 100644 --- a/tools/icon/make-app-icon.py +++ b/tools/icon/make-app-icon.py @@ -8,9 +8,9 @@ python tools/icon/make-app-icon.py Outputs: - apps/windows/Keepassity.Mock/Assets/app.ico (16..256 px frames) - apps/windows/Keepassity.Mock/Assets/app-icon-256.png - apps/windows/Keepassity.Mock/Assets/app-icon-512.png + apps/windows/Keepassity.App/Assets/app.ico (16..256 px frames) + apps/windows/Keepassity.App/Assets/app-icon-256.png + apps/windows/Keepassity.App/Assets/app-icon-512.png No network, no external assets: the mark is drawn geometrically so it stays crisp at 16 px (tray) and 256 px (store/About). @@ -24,7 +24,7 @@ CANVAS = 1024 SUPERSAMPLE = 4 -ASSETS = pathlib.Path("apps/windows/Keepassity.Mock/Assets") +ASSETS = pathlib.Path("apps/windows/Keepassity.App/Assets") # Palette: deep ink to teal, white mark, dark keyhole. INK = (11, 27, 43) diff --git a/tools/installer/verify-install.ps1 b/tools/installer/verify-install.ps1 index 107cb15..9e295ab 100644 --- a/tools/installer/verify-install.ps1 +++ b/tools/installer/verify-install.ps1 @@ -111,7 +111,19 @@ if ($ExpectUninstalled) { Write-Host ("install dir: {0}" -f $InstallDir) if (Test-Path $InstallDir) { - Fail 'program folder removed' ('still exists: ' + $InstallDir) + # The uninstaller removes the program files it installed and leaves + # directories that still contain user data. A directory per se is not a + # failure; a leftover program file is. + $leftProgramFiles = @() + foreach ($name in @('Keepassity.exe', 'Keepassity.Core.dll', 'keepassity_ffi.dll', + 'unins000.exe', 'unins000.dat')) { + if (Test-Path (Join-Path $InstallDir $name)) { $leftProgramFiles += $name } + } + if ($leftProgramFiles.Count -eq 0) { + Pass 'program files removed (folder kept for user data)' + } else { + Fail 'program files removed' (($leftProgramFiles -join ', ') + ' still in ' + $InstallDir) + } } else { Pass 'program folder removed' } diff --git a/vendor/keepassxcr/src/crypto/kdf.rs b/vendor/keepassxcr/src/crypto/kdf.rs index 649803e..f04cec3 100644 --- a/vendor/keepassxcr/src/crypto/kdf.rs +++ b/vendor/keepassxcr/src/crypto/kdf.rs @@ -68,7 +68,7 @@ impl KdfType { } /// Key derivation configuration. -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum KdfConfig { /// AES-KDF configuration. Aes { @@ -164,21 +164,19 @@ impl KdfConfig { } /// Build a default Argon2id configuration. + /// + /// Interoperable baseline (2026-11-15, ADR-0031): 64 MiB / I=3 / P=2 is the + /// KeePassXC default order of magnitude, so a database created here opens on + /// desktop and mobile clients alike. The stronger 128 MiB / I=6 / P=4 set is + /// an explicit, desktop-only choice; it is not the default because a + /// database is shared across devices and the weakest client decides. pub fn default_argon2id() -> Self { - // keepassity calibration (2026-11-09, M5-03): the requirements ask for - // roughly 0.5-1 s of KDF work on the target machine. Measured on the - // reference machine (i7-13700H) with the real reader, 64 MiB / I=3 / P=2 - // opened in ~0.32 s while 128 MiB / I=6 / P=4 opened in ~0.71 s (two - // runs each), so the stronger parameters are the default for new - // databases. Existing databases keep the parameters in their header; - // only files written by this backend start from these values. Method - // and numbers: workshop/docs/verify/perf-2026-11-09.md. Self::Argon2 { kind: KdfType::Argon2id, salt: vec![0u8; 32], - iterations: 6, - memory_kib: 128 * 1024, - parallelism: 4, + iterations: 3, + memory_kib: 64 * 1024, + parallelism: 2, version: 0x13, } } diff --git a/vendor/keepassxcr/src/format/kdbx.rs b/vendor/keepassxcr/src/format/kdbx.rs index 98560a9..82b0e79 100644 --- a/vendor/keepassxcr/src/format/kdbx.rs +++ b/vendor/keepassxcr/src/format/kdbx.rs @@ -350,6 +350,18 @@ fn write_atomic(path: &Path, data: &[u8]) -> AppResult<()> { } pub fn read_kdbx_bytes(data: &[u8], credentials: &Credentials) -> AppResult { + read_kdbx_bytes_with_cache(data, credentials, None) +} + +/// Read a database, optionally reusing a transformed KDF key. The cache is only +/// used for KDBX 4 when its KDF configuration (including salt) matches the +/// header; otherwise the reader falls back to the normal derivation. This is +/// what lets a save verify its own output without paying the KDF a second time. +pub fn read_kdbx_bytes_with_cache( + data: &[u8], + credentials: &Credentials, + cache: Option<&KdfCache>, +) -> AppResult { let mut cursor = Cursor::new(data); let sig1 = read_u32_le(&mut cursor)?; @@ -387,23 +399,32 @@ pub fn read_kdbx_bytes(data: &[u8], credentials: &Credentials) -> AppResult keys.transformed.clone(), + None => Zeroizing::new(cache.expect("cache checked").transformed.to_vec()), + }; + let final_key = match &derived { + Some(keys) => keys.final_key.clone(), + None => build_final_key(&header.master_seed, None, &transformed), + }; let (payload, header_hash) = if version.is_kdbx4() { - let payload = read_kdbx4_payload( - body, - &header, - header_data, - &keys.final_key[..], - &keys.transformed, - )?; + let payload = read_kdbx4_payload(body, &header, header_data, &final_key[..], &transformed)?; (payload, None) } else { - let payload = read_kdbx3_payload(body, &header, &keys.final_key[..])?; + let payload = read_kdbx3_payload(body, &header, &final_key[..])?; (payload, Some(crate::crypto::sha256(header_data))) }; // Only a result that decrypted the file is worth remembering. - credentials.keep(&keys)?; + if let Some(keys) = &derived { + credentials.keep(keys)?; + } let database = read_database( &payload.xml, @@ -424,34 +445,74 @@ pub fn read_kdbx_bytes(data: &[u8], credentials: &Credentials) -> AppResult>, +} + +impl KdfCache { + /// The KDF configuration this cached transform belongs to. + /// + /// Callers that allow the user to change the KDF must compare this with the + /// configuration they are about to write: [`write_kdbx_bytes_with_cache`] + /// takes the KDF from the cache, so a stale cache would silently keep the + /// old parameters. + pub fn kdf(&self) -> &KdfConfig { + &self.kdf + } +} + pub fn write_kdbx_bytes(file: &KdbxFile, credentials: &Credentials) -> AppResult> { + write_kdbx_bytes_with_cache(file, credentials, None).map(|(bytes, _)| bytes) +} + +/// Encrypt `file`, reusing `cache` when supplied and returning the cache for the +/// next save. The output keeps the KDF configuration from the cache (including +/// its salt); a fresh master seed, IV and protected-stream key are still drawn +/// on every save. +pub fn write_kdbx_bytes_with_cache( + file: &KdbxFile, + credentials: &Credentials, + cache: Option<&KdfCache>, +) -> AppResult<(Vec, KdfCache)> { if credentials.is_empty() { return Err(AppError::InvalidInput( "credentials required to encrypt database".to_string(), )); } - let mut kdf = file.kdf.clone(); - randomize_kdf_seed(&mut kdf); + let (kdf, transformed) = match cache { + Some(cache) => ( + cache.kdf.clone(), + Zeroizing::new(cache.transformed.to_vec()), + ), + None => { + let mut kdf = file.kdf.clone(); + randomize_kdf_seed(&mut kdf); + let transformed = credentials.transform_key(&kdf, None)?; + (kdf, transformed) + } + }; let mut master_seed = vec![0u8; 32]; OsRng.fill_bytes(&mut master_seed); - let keys = credentials.derive_keys(file.version, &kdf, &master_seed)?; + let final_key = build_final_key(&master_seed, None, &transformed); let data = if file.version.is_kdbx4() { - write_kdbx4( - file, - &kdf, - &master_seed, - &keys.final_key[..], - &keys.transformed, - )? + write_kdbx4(file, &kdf, &master_seed, &final_key[..], &transformed)? } else { - write_kdbx3(file, &kdf, &master_seed, &keys.final_key[..])? + write_kdbx3(file, &kdf, &master_seed, &final_key[..])? }; - credentials.keep(&keys)?; - Ok(data) + Ok((data, KdfCache { kdf, transformed })) } struct HeaderData { diff --git a/vendor/keepassxcr/src/format/mod.rs b/vendor/keepassxcr/src/format/mod.rs index d84aa57..521401d 100644 --- a/vendor/keepassxcr/src/format/mod.rs +++ b/vendor/keepassxcr/src/format/mod.rs @@ -22,8 +22,8 @@ pub use constants::{ HeaderFieldId, InnerHeaderFieldId, KDBX_SIGNATURE_1, KDBX_SIGNATURE_2, VariantFieldType, }; pub use kdbx::{ - Credentials, CredentialsBuilder, KdbxFile, read_kdbx, read_kdbx_bytes, write_kdbx, - write_kdbx_bytes, + Credentials, CredentialsBuilder, KdbxFile, KdfCache, read_kdbx, read_kdbx_bytes, + read_kdbx_bytes_with_cache, write_kdbx, write_kdbx_bytes, write_kdbx_bytes_with_cache, }; pub use types::{Compression, KdbxVersion}; pub use variant_map::{VariantValue, read_variant_map, write_variant_map}; From 508a6c5a5d54f229dbc016387cc6fe09a4946b89 Mon Sep 17 00:00:00 2001 From: simplenty <52663614+simplenty@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:29:10 +0000 Subject: [PATCH 2/2] Fix the release checks Pass a valid SHA-256 to the FFI sync smoke test and record the unmaintained chrono advisory with a justification. --- crates/ffi/tests/kp_smoke.c | 2 +- deny.toml | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ffi/tests/kp_smoke.c b/crates/ffi/tests/kp_smoke.c index 89a349d..b955a5b 100644 --- a/crates/ffi/tests/kp_smoke.c +++ b/crates/ffi/tests/kp_smoke.c @@ -209,7 +209,7 @@ int main(int argc, char** argv) { "kp_sync_decide"); kp_string_free(decision); check(kp_sync_mark_dirty(handle) == 0, "kp_sync_mark_dirty"); - check(kp_sync_commit(handle, "v2", "sha256") == 0, "kp_sync_commit"); + check(kp_sync_commit(handle, "v2", "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef") == 0, "kp_sync_commit"); char* merged = NULL; size_t merged_len = 0; diff --git a/deny.toml b/deny.toml index 057ebef..dfb723a 100644 --- a/deny.toml +++ b/deny.toml @@ -8,6 +8,11 @@ multiple-versions = "warn" [advisories] yanked = "warn" +# RUSTSEC-2026-0543: chrono is unmaintained (issued 2026-11-17, no patched version). +# chrono 0.4.45 comes in through keepass 0.17.0, which has no maintained release that +# drops it yet. The advisory is informational, not a vulnerability, so it is ignored +# with this note until the dependency graph changes. +ignore = ["RUSTSEC-2026-0543"] [sources] unknown-registry = "deny"