using CrupestApi.Commons; using Dapper; using Microsoft.Data.Sqlite; using Microsoft.Extensions.Options; namespace CrupestApi.Secrets; public class SecretsService : ISecretsService { private readonly IOptionsSnapshot _crupestApiConfig; private readonly ILogger _logger; public SecretsService(IOptionsSnapshot crupestApiConfig, ILogger logger) { _crupestApiConfig = crupestApiConfig; _logger = logger; } private string GetDatabasePath() { return Path.Combine(_crupestApiConfig.Value.DataDir, "secrets.db"); } private async Task EnsureDatabase() { var dataSource = GetDatabasePath(); var connectionStringBuilder = new SqliteConnectionStringBuilder() { DataSource = dataSource }; if (!File.Exists(dataSource)) { _logger.LogInformation("Data source {0} does not exist. Create one.", dataSource); connectionStringBuilder.Mode = SqliteOpenMode.ReadWriteCreate; var connectionString = connectionStringBuilder.ToString(); var connection = new SqliteConnection(connectionString); var transaction = await connection.BeginTransactionAsync(); connection.Execute(@" CREATE TABLE secrets ( Id INTEGER PRIMARY KEY AUTOINCREMENT, Key TEXT NOT NULL, Secret TEXT NOT NULL, Description TEXT NOT NULL, ExpireTime TEXT, Revoked INTEGER NOT NULL, CreateTime TEXT NOT NULL ); CREATE INDEX secrets_key ON secrets (key); INSERT INTO secrets (Key, Secret, Description, ExpireTime, Revoked, CreateTime) VALUES (@SecretManagementKey, 'crupest', 'This is the default secret management key.', NULL, 0, @CreateTime); ", new { SecretManagementKey = SecretsConstants.SecretManagementKey, CreateTime = DateTime.Now.ToString("O"), }); await transaction.CommitAsync(); _logger.LogInformation("{0} created with 'crupest' as the default secret management value. Please immediate revoke it and create a new one.", dataSource); return connection; } else { _logger.LogInformation("Data source {0} already exists. Will use it."); connectionStringBuilder.Mode = SqliteOpenMode.ReadWrite; var connectionString = connectionStringBuilder.ToString(); return new SqliteConnection(connectionString); } } public Task CreateSecretAsync(string key, string description, DateTime? expireTime = null) { throw new NotImplementedException(); } public Task> GetSecretListAsync(bool includeExpired = false, bool includeRevoked = false) { throw new NotImplementedException(); } public Task> GetSecretListByKeyAsync(string key, bool includeExpired = false, bool includeRevoked = false) { throw new NotImplementedException(); } public Task ModifySecretAsync(string secret, SecretModifyRequest modifyRequest) { throw new NotImplementedException(); } public Task RevokeSecretAsync(string secret) { throw new NotImplementedException(); } public Task VerifySecretAsync(string key, string secret) { throw new NotImplementedException(); } public Task VerifySecretForHttpRequestAsync(HttpRequest request, string key, string queryKey = "secret") { throw new NotImplementedException(); } }