54 lines
2.1 KiB
C#
54 lines
2.1 KiB
C#
using Microsoft.Data.Sqlite;
|
|
using System.Security.Cryptography;
|
|
using VolcanicCore.Persistence;
|
|
using VolcanicCore.Persistence.Encryption;
|
|
using VolcanicCore.Persistence.Migrations;
|
|
using VolcanicCore.Persistence.Repositories;
|
|
|
|
namespace VolcanicCore.Tests;
|
|
|
|
public class AdminConfigEncryptionTests
|
|
{
|
|
private static (AdminConfigRepository repo, SqliteConnectionFactory f, EncryptionService enc)
|
|
Setup(IReadOnlySet<string> secureKeys)
|
|
{
|
|
var path = Path.Combine(Path.GetTempPath(), $"vc-{Guid.NewGuid():N}.db");
|
|
var f = new SqliteConnectionFactory(path);
|
|
using (var conn = f.Open())
|
|
new Migrator(new IMigration[] { new Migration001Initial() }).Apply(conn);
|
|
var key = new byte[32]; RandomNumberGenerator.Fill(key);
|
|
var enc = new EncryptionService(key);
|
|
return (new AdminConfigRepository(f, enc, secureKeys), f, enc);
|
|
}
|
|
|
|
[Fact]
|
|
public void Secure_key_is_stored_encrypted_on_disk_but_reads_back_plaintext()
|
|
{
|
|
var secureKeys = new HashSet<string>(StringComparer.Ordinal) { "admin.password_hash_source" };
|
|
var (repo, f, enc) = Setup(secureKeys);
|
|
repo.Set("admin.password_hash_source", "hunter2");
|
|
|
|
// Reads back cleartext
|
|
Assert.Equal("hunter2", repo.Get("admin.password_hash_source"));
|
|
|
|
// Raw disk value is NOT plaintext, and decrypts back to plaintext.
|
|
using var conn = f.Open();
|
|
using var cmd = conn.CreateCommand();
|
|
cmd.CommandText = "SELECT value FROM admin_config WHERE key = 'admin.password_hash_source';";
|
|
var raw = (string)cmd.ExecuteScalar()!;
|
|
Assert.NotEqual("hunter2", raw);
|
|
Assert.Equal("hunter2", enc.Decrypt(raw));
|
|
}
|
|
|
|
[Fact]
|
|
public void Non_secure_key_is_stored_as_plaintext()
|
|
{
|
|
var (repo, f, _) = Setup(new HashSet<string>());
|
|
repo.Set("some.key", "value");
|
|
using var conn = f.Open();
|
|
using var cmd = conn.CreateCommand();
|
|
cmd.CommandText = "SELECT value FROM admin_config WHERE key = 'some.key';";
|
|
Assert.Equal("value", (string)cmd.ExecuteScalar()!);
|
|
}
|
|
}
|