| | | 1 | | using Microsoft.Data.Sqlite; |
| | | 2 | | [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("LOCKnet.Data.Tests")] |
| | | 3 | | |
| | | 4 | | namespace LOCKnet.Data; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Verwaltet die SQLite-Datenbankverbindung und initialisiert das Schema. |
| | | 8 | | /// Erstellt beim ersten Aufruf von <see cref="Initialize"/> alle benötigten Tabellen |
| | | 9 | | /// (Credentials, MasterKey, Settings) mit <c>CREATE TABLE IF NOT EXISTS</c>. |
| | | 10 | | /// </summary> |
| | | 11 | | public class Database |
| | | 12 | | { |
| | | 13 | | private readonly ISqliteConnectionFactory _connectionFactory; |
| | | 14 | | private readonly VaultStorageDescriptor _storage; |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Initialisiert eine neue Instanz von <see cref="Database"/> mit einem Datei-Pfad. |
| | | 18 | | /// </summary> |
| | | 19 | | /// <param name="databasePath"> |
| | | 20 | | /// Pfad zur SQLite-Datenbankdatei (Standard: <c>credentials.db</c> im Arbeitsverzeichnis). |
| | | 21 | | /// </param> |
| | | 22 | | public Database(string databasePath = "credentials.db") |
| | 24 | 23 | | : this(new PlainSqliteConnectionFactory(databasePath)) |
| | 24 | 24 | | { |
| | 24 | 25 | | } |
| | | 26 | | |
| | | 27 | | /// <summary> |
| | | 28 | | /// Initializes a <see cref="Database"/> with a fully-formed connection string. |
| | | 29 | | /// Use this overload in tests when an in-memory connection string is needed. |
| | | 30 | | /// </summary> |
| | | 31 | | internal Database(string connectionString, bool useConnectionStringDirectly) |
| | 62 | 32 | | : this(PlainSqliteConnectionFactory.FromConnectionString(connectionString)) |
| | 62 | 33 | | { |
| | 62 | 34 | | _ = useConnectionStringDirectly; |
| | 62 | 35 | | } |
| | | 36 | | |
| | 159 | 37 | | internal Database(ISqliteConnectionFactory connectionFactory) |
| | 159 | 38 | | { |
| | 159 | 39 | | ArgumentNullException.ThrowIfNull(connectionFactory); |
| | | 40 | | |
| | 159 | 41 | | _connectionFactory = connectionFactory; |
| | 159 | 42 | | _storage = connectionFactory.Storage; |
| | 159 | 43 | | } |
| | | 44 | | |
| | | 45 | | /// <summary> |
| | | 46 | | /// Erstellt alle Tabellen (Credentials, MasterKey, Settings) via <c>CREATE TABLE IF NOT EXISTS</c>. |
| | | 47 | | /// Kann mehrfach aufgerufen werden — idempotent. |
| | | 48 | | /// </summary> |
| | | 49 | | public void Initialize() |
| | 160 | 50 | | { |
| | | 51 | | const string kdfParametersDefault = "TEXT NOT NULL DEFAULT '{\"HashAlgorithm\":\"SHA256\",\"Iterations\":600000,\"Ke |
| | 160 | 52 | | var recovery = StorageRewriteArtifacts.Recover(_storage.DatabasePath); |
| | | 53 | | |
| | 160 | 54 | | using var connection = _connectionFactory.OpenConnection(); |
| | | 55 | | |
| | | 56 | | // Credentials table |
| | 159 | 57 | | using (var cmd = connection.CreateCommand()) |
| | 159 | 58 | | { |
| | 159 | 59 | | cmd.CommandText = @" |
| | 159 | 60 | | CREATE TABLE IF NOT EXISTS Credentials ( |
| | 159 | 61 | | Id INTEGER PRIMARY KEY AUTOINCREMENT, |
| | 159 | 62 | | Title TEXT NOT NULL, |
| | 159 | 63 | | Username TEXT, |
| | 159 | 64 | | EncryptedPassword BLOB NOT NULL, |
| | 159 | 65 | | EncryptedMetadata BLOB, |
| | 159 | 66 | | CredentialUuid TEXT NOT NULL DEFAULT '', |
| | 159 | 67 | | SecretFormatVersion INTEGER NOT NULL DEFAULT 0, |
| | 159 | 68 | | MetadataFormatVersion INTEGER NOT NULL DEFAULT 0, |
| | 159 | 69 | | URL TEXT, |
| | 159 | 70 | | Notes TEXT, |
| | 159 | 71 | | CreatedAt TEXT DEFAULT CURRENT_TIMESTAMP, |
| | 159 | 72 | | UpdatedAt TEXT DEFAULT CURRENT_TIMESTAMP |
| | 159 | 73 | | );"; |
| | 159 | 74 | | cmd.ExecuteNonQuery(); |
| | 159 | 75 | | } |
| | | 76 | | |
| | | 77 | | try |
| | 159 | 78 | | { |
| | 159 | 79 | | using var migrationCommand = connection.CreateCommand(); |
| | 159 | 80 | | migrationCommand.CommandText = "ALTER TABLE Credentials ADD COLUMN IconKey TEXT;"; |
| | 159 | 81 | | migrationCommand.ExecuteNonQuery(); |
| | 153 | 82 | | } |
| | 6 | 83 | | catch (SqliteException) |
| | 6 | 84 | | { |
| | 6 | 85 | | } |
| | | 86 | | |
| | | 87 | | try |
| | 159 | 88 | | { |
| | 159 | 89 | | using var mc = connection.CreateCommand(); |
| | 159 | 90 | | mc.CommandText = "ALTER TABLE Credentials ADD COLUMN CredentialType INTEGER NOT NULL DEFAULT 0;"; |
| | 159 | 91 | | mc.ExecuteNonQuery(); |
| | 153 | 92 | | } |
| | 6 | 93 | | catch (SqliteException) |
| | 6 | 94 | | { |
| | 6 | 95 | | } |
| | | 96 | | |
| | | 97 | | // MasterKey table |
| | 159 | 98 | | using (var cmd = connection.CreateCommand()) |
| | 159 | 99 | | { |
| | 159 | 100 | | cmd.CommandText = @" |
| | 159 | 101 | | CREATE TABLE IF NOT EXISTS MasterKey ( |
| | 159 | 102 | | Id INTEGER PRIMARY KEY CHECK(Id = 1), |
| | 159 | 103 | | PasswordHash BLOB NOT NULL, |
| | 159 | 104 | | FormatVersion INTEGER NOT NULL DEFAULT 1, |
| | 159 | 105 | | KdfIdentifier TEXT NOT NULL DEFAULT 'PBKDF2-SHA256', |
| | 159 | 106 | | KdfParameters TEXT NOT NULL DEFAULT '{""HashAlgorithm"":""SHA256"",""Iterations"":600000,""KeyLength |
| | 159 | 107 | | Salt BLOB NOT NULL, |
| | 159 | 108 | | WrappedVaultKey BLOB, |
| | 159 | 109 | | RequiresStorageCompaction INTEGER NOT NULL DEFAULT 0, |
| | 159 | 110 | | LastStorageCompactionAttemptUtc TEXT, |
| | 159 | 111 | | LastStorageCompactionFailureKind INTEGER NOT NULL DEFAULT 0, |
| | 159 | 112 | | LastStorageCompactionError TEXT, |
| | 159 | 113 | | CreatedAt TEXT DEFAULT CURRENT_TIMESTAMP, |
| | 159 | 114 | | UpdatedAt TEXT DEFAULT CURRENT_TIMESTAMP |
| | 159 | 115 | | );"; |
| | 159 | 116 | | cmd.ExecuteNonQuery(); |
| | 159 | 117 | | } |
| | | 118 | | |
| | 159 | 119 | | TryAddColumn(connection, "MasterKey", "FormatVersion", "INTEGER NOT NULL DEFAULT 1"); |
| | 159 | 120 | | TryAddColumn(connection, "MasterKey", "KdfIdentifier", "TEXT NOT NULL DEFAULT 'PBKDF2-SHA256'"); |
| | 159 | 121 | | TryAddColumn(connection, "MasterKey", "KdfParameters", kdfParametersDefault); |
| | 159 | 122 | | TryAddColumn(connection, "MasterKey", "WrappedVaultKey", "BLOB"); |
| | 159 | 123 | | TryAddColumn(connection, "MasterKey", "UsesLegacyKeyMaterial", "INTEGER NOT NULL DEFAULT 0"); |
| | 159 | 124 | | TryAddColumn(connection, "MasterKey", "RequiresStorageCompaction", "INTEGER NOT NULL DEFAULT 0"); |
| | 159 | 125 | | TryAddColumn(connection, "MasterKey", "LastStorageCompactionAttemptUtc", "TEXT"); |
| | 159 | 126 | | TryAddColumn(connection, "MasterKey", "LastStorageCompactionFailureKind", "INTEGER NOT NULL DEFAULT 0"); |
| | 159 | 127 | | TryAddColumn(connection, "MasterKey", "LastStorageCompactionError", "TEXT"); |
| | 159 | 128 | | TryAddColumn(connection, "MasterKey", "StorageMigrationState", "INTEGER NOT NULL DEFAULT 0"); |
| | 159 | 129 | | TryAddColumn(connection, "MasterKey", "StorageMigrationTargetMode", "INTEGER NOT NULL DEFAULT 0"); |
| | 159 | 130 | | TryAddColumn(connection, "MasterKey", "LastStorageMigrationAttemptUtc", "TEXT"); |
| | 159 | 131 | | TryAddColumn(connection, "MasterKey", "LastStorageMigrationError", "TEXT"); |
| | | 132 | | |
| | 159 | 133 | | TryAddColumn(connection, "Credentials", "CredentialUuid", "TEXT NOT NULL DEFAULT ''"); |
| | 159 | 134 | | TryAddColumn(connection, "Credentials", "SecretFormatVersion", "INTEGER NOT NULL DEFAULT 0"); |
| | 159 | 135 | | TryAddColumn(connection, "Credentials", "EncryptedMetadata", "BLOB"); |
| | 159 | 136 | | TryAddColumn(connection, "Credentials", "MetadataFormatVersion", "INTEGER NOT NULL DEFAULT 0"); |
| | | 137 | | |
| | 159 | 138 | | using (var cmd = connection.CreateCommand()) |
| | 159 | 139 | | { |
| | 159 | 140 | | cmd.CommandText = @" |
| | 159 | 141 | | CREATE UNIQUE INDEX IF NOT EXISTS IX_Credentials_CredentialUuid |
| | 159 | 142 | | ON Credentials(CredentialUuid) |
| | 159 | 143 | | WHERE CredentialUuid <> '';"; |
| | 159 | 144 | | cmd.ExecuteNonQuery(); |
| | 159 | 145 | | } |
| | | 146 | | |
| | 159 | 147 | | using (var cmd = connection.CreateCommand()) |
| | 159 | 148 | | { |
| | 159 | 149 | | cmd.CommandText = @" |
| | 159 | 150 | | CREATE TRIGGER IF NOT EXISTS TRG_Credentials_CurrentMetadata_Insert |
| | 159 | 151 | | BEFORE INSERT ON Credentials |
| | 159 | 152 | | WHEN NEW.MetadataFormatVersion = 1 AND ( |
| | 159 | 153 | | NEW.EncryptedMetadata IS NULL OR length(NEW.EncryptedMetadata) = 0 OR |
| | 159 | 154 | | length(NEW.CredentialUuid) <> 32 OR NEW.CredentialUuid GLOB '*[^0-9A-Fa-f]*' OR |
| | 159 | 155 | | NEW.Title <> '' OR ifnull(NEW.Username, '') <> '' OR ifnull(NEW.URL, '') <> '' OR |
| | 159 | 156 | | ifnull(NEW.Notes, '') <> '' OR ifnull(NEW.IconKey, '') <> '' OR ifnull(NEW.CredentialType, 0) <> 0 |
| | 159 | 157 | | ) |
| | 159 | 158 | | BEGIN |
| | 159 | 159 | | SELECT RAISE(ABORT, 'Current metadata records must not persist plaintext metadata.'); |
| | 159 | 160 | | END;"; |
| | 159 | 161 | | cmd.ExecuteNonQuery(); |
| | 159 | 162 | | } |
| | | 163 | | |
| | 159 | 164 | | using (var cmd = connection.CreateCommand()) |
| | 159 | 165 | | { |
| | 159 | 166 | | cmd.CommandText = @" |
| | 159 | 167 | | CREATE TRIGGER IF NOT EXISTS TRG_Credentials_CurrentMetadata_Update |
| | 159 | 168 | | BEFORE UPDATE ON Credentials |
| | 159 | 169 | | WHEN NEW.MetadataFormatVersion = 1 AND ( |
| | 159 | 170 | | NEW.EncryptedMetadata IS NULL OR length(NEW.EncryptedMetadata) = 0 OR |
| | 159 | 171 | | length(NEW.CredentialUuid) <> 32 OR NEW.CredentialUuid GLOB '*[^0-9A-Fa-f]*' OR |
| | 159 | 172 | | NEW.Title <> '' OR ifnull(NEW.Username, '') <> '' OR ifnull(NEW.URL, '') <> '' OR |
| | 159 | 173 | | ifnull(NEW.Notes, '') <> '' OR ifnull(NEW.IconKey, '') <> '' OR ifnull(NEW.CredentialType, 0) <> 0 |
| | 159 | 174 | | ) |
| | 159 | 175 | | BEGIN |
| | 159 | 176 | | SELECT RAISE(ABORT, 'Current metadata records must not persist plaintext metadata.'); |
| | 159 | 177 | | END;"; |
| | 159 | 178 | | cmd.ExecuteNonQuery(); |
| | 159 | 179 | | } |
| | | 180 | | |
| | | 181 | | // Settings table |
| | 159 | 182 | | using (var cmd = connection.CreateCommand()) |
| | 159 | 183 | | { |
| | 159 | 184 | | cmd.CommandText = @" |
| | 159 | 185 | | CREATE TABLE IF NOT EXISTS Settings ( |
| | 159 | 186 | | Id INTEGER PRIMARY KEY AUTOINCREMENT, |
| | 159 | 187 | | Key TEXT NOT NULL UNIQUE, |
| | 159 | 188 | | Value TEXT NOT NULL, |
| | 159 | 189 | | CreatedAt TEXT DEFAULT CURRENT_TIMESTAMP, |
| | 159 | 190 | | UpdatedAt TEXT DEFAULT CURRENT_TIMESTAMP |
| | 159 | 191 | | );"; |
| | 159 | 192 | | cmd.ExecuteNonQuery(); |
| | 159 | 193 | | } |
| | | 194 | | |
| | 159 | 195 | | if (recovery.ShouldClearPendingState) |
| | 1 | 196 | | StorageRewriteArtifacts.ClearPendingState(connection); |
| | 318 | 197 | | } |
| | | 198 | | |
| | | 199 | | private static void TryAddColumn(SqliteConnection connection, string table, string column, string definition) |
| | 2703 | 200 | | { |
| | | 201 | | try |
| | 2703 | 202 | | { |
| | 2703 | 203 | | using var command = connection.CreateCommand(); |
| | 2703 | 204 | | command.CommandText = $"ALTER TABLE {table} ADD COLUMN {column} {definition};"; |
| | 2703 | 205 | | command.ExecuteNonQuery(); |
| | 765 | 206 | | } |
| | 1938 | 207 | | catch (SqliteException) |
| | 1938 | 208 | | { |
| | 1938 | 209 | | } |
| | 2703 | 210 | | } |
| | | 211 | | } |