Initial version
This commit is contained in:
parent
9f088dddc5
commit
23b1260db6
|
@ -2,7 +2,7 @@
|
||||||
## Ignore Visual Studio temporary files, build results, and
|
## Ignore Visual Studio temporary files, build results, and
|
||||||
## files generated by popular Visual Studio add-ons.
|
## files generated by popular Visual Studio add-ons.
|
||||||
##
|
##
|
||||||
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
|
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
|
||||||
|
|
||||||
# User-specific files
|
# User-specific files
|
||||||
*.rsuser
|
*.rsuser
|
||||||
|
@ -14,9 +14,6 @@
|
||||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||||
*.userprefs
|
*.userprefs
|
||||||
|
|
||||||
# Mono auto generated files
|
|
||||||
mono_crash.*
|
|
||||||
|
|
||||||
# Build results
|
# Build results
|
||||||
[Dd]ebug/
|
[Dd]ebug/
|
||||||
[Dd]ebugPublic/
|
[Dd]ebugPublic/
|
||||||
|
@ -24,14 +21,10 @@ mono_crash.*
|
||||||
[Rr]eleases/
|
[Rr]eleases/
|
||||||
x64/
|
x64/
|
||||||
x86/
|
x86/
|
||||||
[Ww][Ii][Nn]32/
|
|
||||||
[Aa][Rr][Mm]/
|
|
||||||
[Aa][Rr][Mm]64/
|
|
||||||
bld/
|
bld/
|
||||||
[Bb]in/
|
[Bb]in/
|
||||||
[Oo]bj/
|
[Oo]bj/
|
||||||
[Ll]og/
|
[Ll]og/
|
||||||
[Ll]ogs/
|
|
||||||
|
|
||||||
# Visual Studio 2015/2017 cache/options directory
|
# Visual Studio 2015/2017 cache/options directory
|
||||||
.vs/
|
.vs/
|
||||||
|
@ -45,10 +38,9 @@ Generated\ Files/
|
||||||
[Tt]est[Rr]esult*/
|
[Tt]est[Rr]esult*/
|
||||||
[Bb]uild[Ll]og.*
|
[Bb]uild[Ll]og.*
|
||||||
|
|
||||||
# NUnit
|
# NUNIT
|
||||||
*.VisualState.xml
|
*.VisualState.xml
|
||||||
TestResult.xml
|
TestResult.xml
|
||||||
nunit-*.xml
|
|
||||||
|
|
||||||
# Build Results of an ATL Project
|
# Build Results of an ATL Project
|
||||||
[Dd]ebugPS/
|
[Dd]ebugPS/
|
||||||
|
@ -63,9 +55,6 @@ project.lock.json
|
||||||
project.fragment.lock.json
|
project.fragment.lock.json
|
||||||
artifacts/
|
artifacts/
|
||||||
|
|
||||||
# ASP.NET Scaffolding
|
|
||||||
ScaffoldingReadMe.txt
|
|
||||||
|
|
||||||
# StyleCop
|
# StyleCop
|
||||||
StyleCopReport.xml
|
StyleCopReport.xml
|
||||||
|
|
||||||
|
@ -91,7 +80,6 @@ StyleCopReport.xml
|
||||||
*.tmp_proj
|
*.tmp_proj
|
||||||
*_wpftmp.csproj
|
*_wpftmp.csproj
|
||||||
*.log
|
*.log
|
||||||
*.tlog
|
|
||||||
*.vspscc
|
*.vspscc
|
||||||
*.vssscc
|
*.vssscc
|
||||||
.builds
|
.builds
|
||||||
|
@ -133,6 +121,9 @@ _ReSharper*/
|
||||||
*.[Rr]e[Ss]harper
|
*.[Rr]e[Ss]harper
|
||||||
*.DotSettings.user
|
*.DotSettings.user
|
||||||
|
|
||||||
|
# JustCode is a .NET coding add-in
|
||||||
|
.JustCode
|
||||||
|
|
||||||
# TeamCity is a build add-in
|
# TeamCity is a build add-in
|
||||||
_TeamCity*
|
_TeamCity*
|
||||||
|
|
||||||
|
@ -143,11 +134,6 @@ _TeamCity*
|
||||||
.axoCover/*
|
.axoCover/*
|
||||||
!.axoCover/settings.json
|
!.axoCover/settings.json
|
||||||
|
|
||||||
# Coverlet is a free, cross platform Code Coverage Tool
|
|
||||||
coverage*.json
|
|
||||||
coverage*.xml
|
|
||||||
coverage*.info
|
|
||||||
|
|
||||||
# Visual Studio code coverage results
|
# Visual Studio code coverage results
|
||||||
*.coverage
|
*.coverage
|
||||||
*.coveragexml
|
*.coveragexml
|
||||||
|
@ -195,8 +181,6 @@ PublishScripts/
|
||||||
|
|
||||||
# NuGet Packages
|
# NuGet Packages
|
||||||
*.nupkg
|
*.nupkg
|
||||||
# NuGet Symbol Packages
|
|
||||||
*.snupkg
|
|
||||||
# The packages folder can be ignored because of Package Restore
|
# The packages folder can be ignored because of Package Restore
|
||||||
**/[Pp]ackages/*
|
**/[Pp]ackages/*
|
||||||
# except build/, which is used as an MSBuild target.
|
# except build/, which is used as an MSBuild target.
|
||||||
|
@ -221,14 +205,12 @@ BundleArtifacts/
|
||||||
Package.StoreAssociation.xml
|
Package.StoreAssociation.xml
|
||||||
_pkginfo.txt
|
_pkginfo.txt
|
||||||
*.appx
|
*.appx
|
||||||
*.appxbundle
|
|
||||||
*.appxupload
|
|
||||||
|
|
||||||
# Visual Studio cache files
|
# Visual Studio cache files
|
||||||
# files ending in .cache can be ignored
|
# files ending in .cache can be ignored
|
||||||
*.[Cc]ache
|
*.[Cc]ache
|
||||||
# but keep track of directories ending in .cache
|
# but keep track of directories ending in .cache
|
||||||
!?*.[Cc]ache/
|
!*.[Cc]ache/
|
||||||
|
|
||||||
# Others
|
# Others
|
||||||
ClientBin/
|
ClientBin/
|
||||||
|
@ -272,9 +254,6 @@ ServiceFabricBackup/
|
||||||
*.bim.layout
|
*.bim.layout
|
||||||
*.bim_*.settings
|
*.bim_*.settings
|
||||||
*.rptproj.rsuser
|
*.rptproj.rsuser
|
||||||
*- [Bb]ackup.rdl
|
|
||||||
*- [Bb]ackup ([0-9]).rdl
|
|
||||||
*- [Bb]ackup ([0-9][0-9]).rdl
|
|
||||||
|
|
||||||
# Microsoft Fakes
|
# Microsoft Fakes
|
||||||
FakesAssemblies/
|
FakesAssemblies/
|
||||||
|
@ -295,17 +274,6 @@ node_modules/
|
||||||
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||||
*.vbw
|
*.vbw
|
||||||
|
|
||||||
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
|
|
||||||
*.vbp
|
|
||||||
|
|
||||||
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
|
|
||||||
*.dsw
|
|
||||||
*.dsp
|
|
||||||
|
|
||||||
# Visual Studio 6 technical files
|
|
||||||
*.ncb
|
|
||||||
*.aps
|
|
||||||
|
|
||||||
# Visual Studio LightSwitch build output
|
# Visual Studio LightSwitch build output
|
||||||
**/*.HTMLClient/GeneratedArtifacts
|
**/*.HTMLClient/GeneratedArtifacts
|
||||||
**/*.DesktopClient/GeneratedArtifacts
|
**/*.DesktopClient/GeneratedArtifacts
|
||||||
|
@ -321,6 +289,10 @@ paket-files/
|
||||||
# FAKE - F# Make
|
# FAKE - F# Make
|
||||||
.fake/
|
.fake/
|
||||||
|
|
||||||
|
# JetBrains Rider
|
||||||
|
.idea/
|
||||||
|
*.sln.iml
|
||||||
|
|
||||||
# CodeRush personal settings
|
# CodeRush personal settings
|
||||||
.cr/personal
|
.cr/personal
|
||||||
|
|
||||||
|
@ -362,53 +334,10 @@ ASALocalRun/
|
||||||
# Local History for Visual Studio
|
# Local History for Visual Studio
|
||||||
.localhistory/
|
.localhistory/
|
||||||
|
|
||||||
# Visual Studio History (VSHistory) files
|
|
||||||
.vshistory/
|
|
||||||
|
|
||||||
# BeatPulse healthcheck temp database
|
|
||||||
healthchecksdb
|
|
||||||
|
|
||||||
# Backup folder for Package Reference Convert tool in Visual Studio 2017
|
|
||||||
MigrationBackup/
|
|
||||||
|
|
||||||
# Ionide (cross platform F# VS Code tools) working folder
|
|
||||||
.ionide/
|
|
||||||
|
|
||||||
# Fody - auto-generated XML schema
|
|
||||||
FodyWeavers.xsd
|
|
||||||
|
|
||||||
# VS Code files for those working on multiple tools
|
|
||||||
.vscode/*
|
|
||||||
!.vscode/settings.json
|
|
||||||
!.vscode/tasks.json
|
|
||||||
!.vscode/launch.json
|
|
||||||
!.vscode/extensions.json
|
|
||||||
*.code-workspace
|
|
||||||
|
|
||||||
# Local History for Visual Studio Code
|
|
||||||
.history/
|
|
||||||
|
|
||||||
# Windows Installer files from build outputs
|
|
||||||
*.cab
|
|
||||||
*.msi
|
|
||||||
*.msix
|
|
||||||
*.msm
|
|
||||||
*.msp
|
|
||||||
|
|
||||||
# JetBrains Rider
|
|
||||||
*.sln.iml
|
|
||||||
|
|
||||||
# ---> VisualStudioCode
|
# ---> VisualStudioCode
|
||||||
.vscode/*
|
.vscode/*
|
||||||
!.vscode/settings.json
|
!.vscode/settings.json
|
||||||
!.vscode/tasks.json
|
!.vscode/tasks.json
|
||||||
!.vscode/launch.json
|
!.vscode/launch.json
|
||||||
!.vscode/extensions.json
|
!.vscode/extensions.json
|
||||||
!.vscode/*.code-snippets
|
|
||||||
|
|
||||||
# Local History for Visual Studio Code
|
|
||||||
.history/
|
|
||||||
|
|
||||||
# Built Visual Studio Code Extensions
|
|
||||||
*.vsix
|
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,52 @@
|
||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<PropertyGroup>
|
||||||
|
<LangVersion>Latest</LangVersion>
|
||||||
|
<TargetFramework>netstandard2.1</TargetFramework>
|
||||||
|
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||||
|
<PackageId>EonaCat.SecretVault.Client</PackageId>
|
||||||
|
<Authors>EonaCat (Jeroen Saey)</Authors>
|
||||||
|
<Company>EonaCat (Jeroen Saey)</Company>
|
||||||
|
<Product>EonaCat.SecretVault.Client</Product>
|
||||||
|
<Copyright>EonaCat (Jeroen Saey)</Copyright>
|
||||||
|
<PackageProjectUrl>https://www.nuget.org/packages/EonaCat.SecretVault.Client/</PackageProjectUrl>
|
||||||
|
<PackageTags>EonaCat, Secret, client, Security, Vault, .NET Standard, SecretVault, Jeroen, Saey, Library</PackageTags>
|
||||||
|
<PackageReleaseNotes></PackageReleaseNotes>
|
||||||
|
<Description>Secure vault client.</Description>
|
||||||
|
<IsPackable>true</IsPackable>
|
||||||
|
<Version>1.0.0</Version>
|
||||||
|
<AssemblyVersion>1.0.0</AssemblyVersion>
|
||||||
|
<FileVersion>1.0.0</FileVersion>
|
||||||
|
<PackageIcon>icon.png</PackageIcon>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<GenerateAssemblyInfo>True</GenerateAssemblyInfo>
|
||||||
|
<GenerateDocumentationFile>True</GenerateDocumentationFile>
|
||||||
|
<PackageReadmeFile>README.md</PackageReadmeFile>
|
||||||
|
<SignAssembly>False</SignAssembly>
|
||||||
|
<Title>EonaCat.SecretVault.Client</Title>
|
||||||
|
<PackageRequireLicenseAcceptance>True</PackageRequireLicenseAcceptance>
|
||||||
|
<PackageLicenseFile>LICENSE</PackageLicenseFile>
|
||||||
|
<RepositoryUrl>https://git.saey.me/EonaCat/EonaCat.SecretVault.git</RepositoryUrl>
|
||||||
|
<RepositoryType>git</RepositoryType>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Include="..\icon.png">
|
||||||
|
<Pack>True</Pack>
|
||||||
|
<PackagePath>\</PackagePath>
|
||||||
|
</None>
|
||||||
|
<None Include="..\LICENSE">
|
||||||
|
<Pack>True</Pack>
|
||||||
|
<PackagePath>\</PackagePath>
|
||||||
|
</None>
|
||||||
|
<None Include="..\README.md">
|
||||||
|
<Pack>True</Pack>
|
||||||
|
<PackagePath>\</PackagePath>
|
||||||
|
</None>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="EonaCat.Json" Version="1.1.9" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
|
@ -0,0 +1,118 @@
|
||||||
|
using System;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Security.Cryptography.X509Certificates;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
namespace EonaCat.SecretVault.Client
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Client for securely storing and retrieving secrets from a SecretVault server.
|
||||||
|
/// </summary>
|
||||||
|
public class SecretVaultClient : IDisposable
|
||||||
|
{
|
||||||
|
private readonly HttpClient _http;
|
||||||
|
private readonly string _baseUrl;
|
||||||
|
|
||||||
|
public SecretVaultClient(string baseUrl, string apiKey, bool isHttps = true, X509Certificate2? expectedCert = null)
|
||||||
|
{
|
||||||
|
if (isHttps)
|
||||||
|
{
|
||||||
|
if (!baseUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("Base URL must use HTTPS for secure communication.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_baseUrl = baseUrl.TrimEnd('/') + "/";
|
||||||
|
|
||||||
|
var handler = new HttpClientHandler();
|
||||||
|
|
||||||
|
if (expectedCert != null)
|
||||||
|
{
|
||||||
|
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
|
||||||
|
{
|
||||||
|
return cert != null && cert.GetCertHashString() == expectedCert.GetCertHashString();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
_http = new HttpClient(handler)
|
||||||
|
{
|
||||||
|
BaseAddress = new Uri(_baseUrl),
|
||||||
|
Timeout = TimeSpan.FromSeconds(10)
|
||||||
|
};
|
||||||
|
|
||||||
|
_http.DefaultRequestHeaders.Add("X-Api-Key", apiKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
public SecretVaultClient(HttpClient httpClient, string apiKey, bool isHttps = true, X509Certificate2? expectedCert = null)
|
||||||
|
{
|
||||||
|
_http = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
|
||||||
|
|
||||||
|
if (isHttps)
|
||||||
|
{
|
||||||
|
if (!_http.BaseAddress.AbsoluteUri.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("Base URL must use HTTPS for secure communication.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(apiKey))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("API key cannot be null or empty", nameof(apiKey));
|
||||||
|
}
|
||||||
|
_http.DefaultRequestHeaders.Add("X-Api-Key", apiKey);
|
||||||
|
|
||||||
|
if (expectedCert != null)
|
||||||
|
{
|
||||||
|
var handler = new HttpClientHandler();
|
||||||
|
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
|
||||||
|
{
|
||||||
|
return cert != null && cert.GetCertHashString() == expectedCert.GetCertHashString();
|
||||||
|
};
|
||||||
|
|
||||||
|
// Dispose the old HttpClient if it exists
|
||||||
|
_http?.Dispose();
|
||||||
|
_http = new HttpClient(handler)
|
||||||
|
{
|
||||||
|
BaseAddress = _http.BaseAddress,
|
||||||
|
Timeout = _http.Timeout,
|
||||||
|
MaxResponseContentBufferSize = _http.MaxResponseContentBufferSize,
|
||||||
|
};
|
||||||
|
|
||||||
|
_http.DefaultRequestHeaders.Add("X-Api-Key", apiKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task StoreAsync(string key, string secret)
|
||||||
|
{
|
||||||
|
var content = new StringContent($"\"{secret}\"");
|
||||||
|
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||||
|
await _http.PostAsync($"api/secrets/store?key={Uri.EscapeDataString(key)}", content);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task DeleteAsync(string key)
|
||||||
|
{
|
||||||
|
await _http.DeleteAsync($"api/secrets/delete?key={Uri.EscapeDataString(key)}");
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<string?> RetrieveAsync(string key)
|
||||||
|
{
|
||||||
|
var res = await _http.GetAsync($"api/secrets/retrieve?key={Uri.EscapeDataString(key)}");
|
||||||
|
if (!res.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await res.Content.ReadAsStringAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_http.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
|
||||||
|
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||||
|
# Visual Studio Version 17
|
||||||
|
VisualStudioVersion = 17.0.31903.59
|
||||||
|
MinimumVisualStudioVersion = 10.0.40219.1
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.SecretVault", "EonaCat.SecretVault\EonaCat.SecretVault.csproj", "{23C4BE6C-25FF-A073-66C6-741A81C75A4A}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.SecretVault.Client", "EonaCat.SecretVault.Client\EonaCat.SecretVault.Client.csproj", "{F354C53D-DFDE-41BC-993B-1C520FCFA304}"
|
||||||
|
EndProject
|
||||||
|
Global
|
||||||
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
|
Debug|Any CPU = Debug|Any CPU
|
||||||
|
Release|Any CPU = Release|Any CPU
|
||||||
|
EndGlobalSection
|
||||||
|
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||||
|
{23C4BE6C-25FF-A073-66C6-741A81C75A4A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{23C4BE6C-25FF-A073-66C6-741A81C75A4A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{23C4BE6C-25FF-A073-66C6-741A81C75A4A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{23C4BE6C-25FF-A073-66C6-741A81C75A4A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{F354C53D-DFDE-41BC-993B-1C520FCFA304}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{F354C53D-DFDE-41BC-993B-1C520FCFA304}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{F354C53D-DFDE-41BC-993B-1C520FCFA304}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{F354C53D-DFDE-41BC-993B-1C520FCFA304}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
EndGlobalSection
|
||||||
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
|
HideSolutionNode = FALSE
|
||||||
|
EndGlobalSection
|
||||||
|
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||||
|
SolutionGuid = {B839F1D9-578B-4D9F-A8E5-43763F9B1C57}
|
||||||
|
EndGlobalSection
|
||||||
|
EndGlobal
|
|
@ -0,0 +1,96 @@
|
||||||
|
using EonaCat.SecretVault.Data;
|
||||||
|
using EonaCat.SecretVault.Helpers;
|
||||||
|
using EonaCat.SecretVault.Middleware;
|
||||||
|
using EonaCat.SecretVault.Models;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
namespace EonaCat.SecretVault.Controllers
|
||||||
|
{
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class AdminController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly SecretDbContext _db;
|
||||||
|
public AdminController(SecretDbContext db) => _db = db;
|
||||||
|
|
||||||
|
[HttpPost("generate-key")]
|
||||||
|
[RequireRole(ApiRole.Admin)]
|
||||||
|
public IActionResult GenerateKey([FromQuery] ApiRole role)
|
||||||
|
{
|
||||||
|
var tenantId = HttpContext.Items["TenantId"]?.ToString()!;
|
||||||
|
var newKey = Guid.NewGuid().ToString("N");
|
||||||
|
|
||||||
|
var rootKey = Environment.GetEnvironmentVariable("ROOT_PROTECTOR_KEY")!;
|
||||||
|
var tenantKey = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32));
|
||||||
|
|
||||||
|
var encryptedTenantKey = TenantKeyProtector.EncryptTenantKey(tenantKey, rootKey);
|
||||||
|
var apiKey = GenerateApiKey();
|
||||||
|
var apiKeyHash = HashApiKey(apiKey);
|
||||||
|
|
||||||
|
_db.ApiKeys.Add(new TenantApiKey
|
||||||
|
{
|
||||||
|
ApiKey = newKey,
|
||||||
|
TenantId = tenantId,
|
||||||
|
EncryptionKey = tenantKey,
|
||||||
|
EncryptedEncryptionKey = encryptedTenantKey,
|
||||||
|
CreatedAt = DateTime.UtcNow,
|
||||||
|
Scope = "read,write",
|
||||||
|
ApiKeyHash = apiKeyHash,
|
||||||
|
Role = role,
|
||||||
|
IsActive = true,
|
||||||
|
});
|
||||||
|
_db.SaveChanges();
|
||||||
|
|
||||||
|
return Ok(new { apiKey = newKey, role });
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpDelete("revoke-key")]
|
||||||
|
[RequireRole(ApiRole.Admin)]
|
||||||
|
public IActionResult RevokeKey([FromQuery] string key)
|
||||||
|
{
|
||||||
|
var tenantId = HttpContext.Items["TenantId"]?.ToString()!;
|
||||||
|
var entry = _db.ApiKeys.FirstOrDefault(k => k.ApiKey == key && k.TenantId == tenantId);
|
||||||
|
if (entry == null)
|
||||||
|
{
|
||||||
|
return NotFound("Key not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
entry.IsActive = false;
|
||||||
|
_db.SaveChanges();
|
||||||
|
|
||||||
|
return Ok("Key revoked");
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("keys")]
|
||||||
|
[RequireRole(ApiRole.Admin)]
|
||||||
|
public IActionResult ListKeys()
|
||||||
|
{
|
||||||
|
var tenantId = HttpContext.Items["TenantId"]?.ToString()!;
|
||||||
|
var keys = _db.ApiKeys
|
||||||
|
.Where(k => k.TenantId == tenantId)
|
||||||
|
.Select(k => new { k.ApiKey, k.Role, k.IsActive, k.CreatedAt })
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
return Ok(keys);
|
||||||
|
}
|
||||||
|
|
||||||
|
string GenerateApiKey()
|
||||||
|
{
|
||||||
|
return Convert.ToBase64String(RandomNumberGenerator.GetBytes(32));
|
||||||
|
}
|
||||||
|
|
||||||
|
string HashApiKey(string apiKey)
|
||||||
|
{
|
||||||
|
using var sha256 = SHA256.Create();
|
||||||
|
var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(apiKey));
|
||||||
|
return Convert.ToBase64String(hash);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,55 @@
|
||||||
|
using EonaCat.SecretVault.Services;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
namespace EonaCat.SecretVault.Controllers
|
||||||
|
{
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class SecretsController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly SecretService _svc;
|
||||||
|
public SecretsController(SecretService svc) => _svc = svc;
|
||||||
|
|
||||||
|
[HttpPost("store")]
|
||||||
|
public async Task<IActionResult> Store([FromQuery] string key, [FromBody] string secret)
|
||||||
|
{
|
||||||
|
var user = HttpContext.Items["User"]?.ToString() ?? "unknown";
|
||||||
|
var tenant = HttpContext.Items["TenantId"]?.ToString() ?? "default";
|
||||||
|
await _svc.StoreAsync(tenant, key, secret, user);
|
||||||
|
return Ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpDelete("delete")]
|
||||||
|
public async Task<IActionResult> Delete([FromQuery] string key)
|
||||||
|
{
|
||||||
|
var user = HttpContext.Items["User"]?.ToString() ?? "unknown";
|
||||||
|
var tenant = HttpContext.Items["TenantId"]?.ToString() ?? "default";
|
||||||
|
var deleted = await _svc.DeleteAsync(tenant, key, user);
|
||||||
|
if (!deleted)
|
||||||
|
{
|
||||||
|
return NotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("retrieve")]
|
||||||
|
public IActionResult Retrieve([FromQuery] string key)
|
||||||
|
{
|
||||||
|
var user = HttpContext.Items["User"]?.ToString() ?? "unknown";
|
||||||
|
var tenant = HttpContext.Items["TenantId"]?.ToString() ?? "default";
|
||||||
|
var secret = _svc.Retrieve(tenant, key, user);
|
||||||
|
if (secret == null)
|
||||||
|
{
|
||||||
|
return NotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(secret);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,16 @@
|
||||||
|
using EonaCat.SecretVault.Models;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
namespace EonaCat.SecretVault.Data
|
||||||
|
{
|
||||||
|
public class SecretDbContext : DbContext
|
||||||
|
{
|
||||||
|
public SecretDbContext(DbContextOptions<SecretDbContext> options) : base(options) { }
|
||||||
|
public DbSet<SecretModel> Secrets => Set<SecretModel>();
|
||||||
|
public DbSet<AuditLog> AuditLogs => Set<AuditLog>();
|
||||||
|
public DbSet<TenantApiKey> ApiKeys => Set<TenantApiKey>();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,53 @@
|
||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<PropertyGroup>
|
||||||
|
<LangVersion>Latest</LangVersion>
|
||||||
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
|
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||||
|
<PackageId>EonaCat.SecretVault</PackageId>
|
||||||
|
<Authors>EonaCat (Jeroen Saey)</Authors>
|
||||||
|
<Company>EonaCat (Jeroen Saey)</Company>
|
||||||
|
<Product>EonaCat.SecretVault</Product>
|
||||||
|
<Copyright>EonaCat (Jeroen Saey)</Copyright>
|
||||||
|
<PackageProjectUrl>https://www.nuget.org/packages/EonaCat.SecretVault/</PackageProjectUrl>
|
||||||
|
<PackageTags>EonaCat, Secret, server, Security, Vault, .NET Standard, SecretVault, Jeroen, Saey, Library</PackageTags>
|
||||||
|
<PackageReleaseNotes></PackageReleaseNotes>
|
||||||
|
<Description>Secure multi-tenant vault server with API key authentication and auditing.</Description>
|
||||||
|
<IsPackable>true</IsPackable>
|
||||||
|
<Version>1.0.0</Version>
|
||||||
|
<AssemblyVersion>1.0.0</AssemblyVersion>
|
||||||
|
<FileVersion>1.0.0</FileVersion>
|
||||||
|
<PackageIcon>icon.png</PackageIcon>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<GenerateAssemblyInfo>True</GenerateAssemblyInfo>
|
||||||
|
<GenerateDocumentationFile>True</GenerateDocumentationFile>
|
||||||
|
<PackageReadmeFile>README.md</PackageReadmeFile>
|
||||||
|
<SignAssembly>False</SignAssembly>
|
||||||
|
<Title>EonaCat.SecretVault</Title>
|
||||||
|
<PackageRequireLicenseAcceptance>True</PackageRequireLicenseAcceptance>
|
||||||
|
<PackageLicenseFile>LICENSE</PackageLicenseFile>
|
||||||
|
<RepositoryUrl>https://git.saey.me/EonaCat/EonaCat.SecretVault.git</RepositoryUrl>
|
||||||
|
<RepositoryType>git</RepositoryType>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Include="..\icon.png">
|
||||||
|
<Pack>True</Pack>
|
||||||
|
<PackagePath>\</PackagePath>
|
||||||
|
</None>
|
||||||
|
<None Include="..\LICENSE">
|
||||||
|
<Pack>True</Pack>
|
||||||
|
<PackagePath>\</PackagePath>
|
||||||
|
</None>
|
||||||
|
<None Include="..\README.md">
|
||||||
|
<Pack>True</Pack>
|
||||||
|
<PackagePath>\</PackagePath>
|
||||||
|
</None>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.6" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
|
@ -0,0 +1,33 @@
|
||||||
|
using System;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
namespace EonaCat.SecretVault.Helpers
|
||||||
|
{
|
||||||
|
public static class TenantKeyProtector
|
||||||
|
{
|
||||||
|
public static string EncryptTenantKey(string base64Key, string rootKeyBase64)
|
||||||
|
{
|
||||||
|
var key = Convert.FromBase64String(rootKeyBase64);
|
||||||
|
using var aes = Aes.Create();
|
||||||
|
aes.Key = key;
|
||||||
|
aes.GenerateIV();
|
||||||
|
var encryptor = aes.CreateEncryptor();
|
||||||
|
var encrypted = encryptor.TransformFinalBlock(Convert.FromBase64String(base64Key), 0, 32);
|
||||||
|
return $"{Convert.ToBase64String(aes.IV)}.{Convert.ToBase64String(encrypted)}";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string DecryptTenantKey(string encryptedPayload, string rootKeyBase64)
|
||||||
|
{
|
||||||
|
var key = Convert.FromBase64String(rootKeyBase64);
|
||||||
|
var parts = encryptedPayload.Split('.');
|
||||||
|
var iv = Convert.FromBase64String(parts[0]);
|
||||||
|
var encrypted = Convert.FromBase64String(parts[1]);
|
||||||
|
using var aes = Aes.Create();
|
||||||
|
aes.Key = key;
|
||||||
|
aes.IV = iv;
|
||||||
|
var decryptor = aes.CreateDecryptor();
|
||||||
|
var decrypted = decryptor.TransformFinalBlock(encrypted, 0, encrypted.Length);
|
||||||
|
return Convert.ToBase64String(decrypted);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,57 @@
|
||||||
|
using EonaCat.SecretVault.Data;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
namespace EonaCat.SecretVault.Middleware
|
||||||
|
{
|
||||||
|
public class ApiKeyMiddleware
|
||||||
|
{
|
||||||
|
private readonly RequestDelegate _next;
|
||||||
|
private const string ApiKeyHeaderName = "X-Api-Key";
|
||||||
|
|
||||||
|
public ApiKeyMiddleware(RequestDelegate next) => _next = next;
|
||||||
|
|
||||||
|
public async Task InvokeAsync(HttpContext context)
|
||||||
|
{
|
||||||
|
if (!context.Request.Headers.TryGetValue(ApiKeyHeaderName, out var extractedApiKey))
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = 401;
|
||||||
|
await context.Response.WriteAsync("API Key is missing");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var db = context.RequestServices.GetRequiredService<SecretDbContext>();
|
||||||
|
var tenant = db.ApiKeys.AsEnumerable()
|
||||||
|
.FirstOrDefault(k => VerifyApiKey(extractedApiKey, k.ApiKeyHash));
|
||||||
|
|
||||||
|
if (tenant == null)
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = 403;
|
||||||
|
await context.Response.WriteAsync("Unauthorized API Key");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
context.Items["TenantId"] = tenant.TenantId;
|
||||||
|
context.Items["User"] = "apikey-user";
|
||||||
|
context.Items["Scope"] = tenant.Scope;
|
||||||
|
await _next(context);
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool VerifyApiKey(string apiKey, string storedHash)
|
||||||
|
{
|
||||||
|
using var sha256 = SHA256.Create();
|
||||||
|
var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(apiKey));
|
||||||
|
var hashBase64 = Convert.ToBase64String(hash);
|
||||||
|
return hashBase64 == storedHash;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,39 @@
|
||||||
|
using EonaCat.SecretVault.Models;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Filters;
|
||||||
|
using System;
|
||||||
|
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
namespace EonaCat.SecretVault.Middleware
|
||||||
|
{
|
||||||
|
[AttributeUsage(AttributeTargets.Method)]
|
||||||
|
public class RequireRoleAttribute : Attribute, IAuthorizationFilter
|
||||||
|
{
|
||||||
|
private readonly ApiRole _requiredRole;
|
||||||
|
|
||||||
|
public RequireRoleAttribute(ApiRole requiredRole)
|
||||||
|
{
|
||||||
|
_requiredRole = requiredRole;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnAuthorization(AuthorizationFilterContext context)
|
||||||
|
{
|
||||||
|
if (!context.HttpContext.Items.TryGetValue("Role", out var roleObj))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Enum.TryParse(roleObj?.ToString(), out ApiRole actualRole))
|
||||||
|
{
|
||||||
|
if (actualRole >= _requiredRole)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
context.Result = new Microsoft.AspNetCore.Mvc.ForbidResult();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,12 @@
|
||||||
|
namespace EonaCat.SecretVault.Models
|
||||||
|
{
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
public enum ApiRole
|
||||||
|
{
|
||||||
|
Reader,
|
||||||
|
Writer,
|
||||||
|
Admin
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
using System;
|
||||||
|
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
namespace EonaCat.SecretVault.Models
|
||||||
|
{
|
||||||
|
public class AuditLog
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public string TenantId { get; set; } = null!;
|
||||||
|
public string Action { get; set; } = null!;
|
||||||
|
public string Key { get; set; } = null!;
|
||||||
|
public string PerformedBy { get; set; } = null!;
|
||||||
|
public DateTime Timestamp { get; set; }
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,16 @@
|
||||||
|
using System;
|
||||||
|
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
namespace EonaCat.SecretVault.Models
|
||||||
|
{
|
||||||
|
public class SecretModel
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public string TenantId { get; set; } = null!;
|
||||||
|
public string Key { get; set; } = null!;
|
||||||
|
public string EncryptedValue { get; set; } = null!;
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
using System;
|
||||||
|
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
namespace EonaCat.SecretVault.Models
|
||||||
|
{
|
||||||
|
public class TenantApiKey
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public string ApiKey { get; set; } = null!;
|
||||||
|
public string TenantId { get; set; } = null!;
|
||||||
|
public string ApiKeyHash { get; set; } = null!;
|
||||||
|
public string EncryptionKey { get; set; } = null!;
|
||||||
|
public string EncryptedEncryptionKey { get; set; } = null!;
|
||||||
|
public ApiRole Role { get; set; }
|
||||||
|
public bool IsActive { get; set; } = true;
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||||
|
public string Scope { get; set; } = "read,write";
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,12 @@
|
||||||
|
{
|
||||||
|
"profiles": {
|
||||||
|
"EonaCat.SecretVault": {
|
||||||
|
"commandName": "Project",
|
||||||
|
"launchBrowser": true,
|
||||||
|
"environmentVariables": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
|
},
|
||||||
|
"applicationUrl": "https://localhost:57884;http://localhost:57885"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,25 @@
|
||||||
|
using System;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace EonaCat.SecretVault.Services
|
||||||
|
{
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
public class HmacService
|
||||||
|
{
|
||||||
|
private readonly byte[] _hmacKey;
|
||||||
|
public HmacService()
|
||||||
|
{
|
||||||
|
_hmacKey = Convert.FromBase64String(Environment.GetEnvironmentVariable("VAULT_HMAC_KEY")!);
|
||||||
|
}
|
||||||
|
|
||||||
|
public string ComputeHmac(string input)
|
||||||
|
{
|
||||||
|
using var hmac = new HMACSHA256(_hmacKey);
|
||||||
|
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(input));
|
||||||
|
return Convert.ToBase64String(hash);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,129 @@
|
||||||
|
using EonaCat.SecretVault.Data;
|
||||||
|
using EonaCat.SecretVault.Helpers;
|
||||||
|
using EonaCat.SecretVault.Models;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace EonaCat.SecretVault.Services
|
||||||
|
{
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
public class SecretService
|
||||||
|
{
|
||||||
|
private readonly SecretDbContext _db;
|
||||||
|
private readonly string _rootKeyBase64;
|
||||||
|
|
||||||
|
public SecretService(IConfiguration config, SecretDbContext db)
|
||||||
|
{
|
||||||
|
_db = db;
|
||||||
|
_rootKeyBase64 = Environment.GetEnvironmentVariable("ROOT_PROTECTOR_KEY")
|
||||||
|
?? throw new Exception("ROOT_PROTECTOR_KEY env var is missing");
|
||||||
|
}
|
||||||
|
|
||||||
|
private byte[] GetTenantKey(string tenantId)
|
||||||
|
{
|
||||||
|
var tenant = _db.ApiKeys.FirstOrDefault(t => t.TenantId == tenantId);
|
||||||
|
if (tenant == null)
|
||||||
|
{
|
||||||
|
throw new Exception("Tenant API key not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
var decryptedBase64 = TenantKeyProtector.DecryptTenantKey(tenant.EncryptedEncryptionKey, _rootKeyBase64);
|
||||||
|
return Convert.FromBase64String(decryptedBase64);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task StoreAsync(string tenantId, string key, string secret, string user)
|
||||||
|
{
|
||||||
|
var tenantKey = GetTenantKey(tenantId);
|
||||||
|
|
||||||
|
using var aes = Aes.Create();
|
||||||
|
aes.Key = tenantKey;
|
||||||
|
aes.GenerateIV();
|
||||||
|
|
||||||
|
var encryptor = aes.CreateEncryptor();
|
||||||
|
var plain = Encoding.UTF8.GetBytes(secret);
|
||||||
|
var cipher = encryptor.TransformFinalBlock(plain, 0, plain.Length);
|
||||||
|
var payload = Convert.ToBase64String(aes.IV) + "." + Convert.ToBase64String(cipher);
|
||||||
|
|
||||||
|
var model = new SecretModel { TenantId = tenantId, Key = key, EncryptedValue = payload, CreatedAt = DateTime.UtcNow };
|
||||||
|
_db.Secrets.Add(model);
|
||||||
|
|
||||||
|
_db.AuditLogs.Add(new AuditLog
|
||||||
|
{
|
||||||
|
TenantId = tenantId,
|
||||||
|
Action = "Store",
|
||||||
|
Key = key,
|
||||||
|
PerformedBy = user,
|
||||||
|
Timestamp = DateTime.UtcNow
|
||||||
|
});
|
||||||
|
|
||||||
|
await _db.SaveChangesAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public string? Retrieve(string tenantId, string key, string user)
|
||||||
|
{
|
||||||
|
var tenantKey = GetTenantKey(tenantId);
|
||||||
|
|
||||||
|
var model = _db.Secrets
|
||||||
|
.Where(s => s.TenantId == tenantId && s.Key == key)
|
||||||
|
.OrderByDescending(s => s.CreatedAt)
|
||||||
|
.FirstOrDefault();
|
||||||
|
if (model == null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var parts = model.EncryptedValue.Split('.');
|
||||||
|
var iv = Convert.FromBase64String(parts[0]);
|
||||||
|
var cipher = Convert.FromBase64String(parts[1]);
|
||||||
|
|
||||||
|
using var aes = Aes.Create();
|
||||||
|
aes.Key = tenantKey;
|
||||||
|
aes.IV = iv;
|
||||||
|
var decryptor = aes.CreateDecryptor();
|
||||||
|
var decrypted = decryptor.TransformFinalBlock(cipher, 0, cipher.Length);
|
||||||
|
|
||||||
|
_db.AuditLogs.Add(new AuditLog
|
||||||
|
{
|
||||||
|
TenantId = tenantId,
|
||||||
|
Action = "Retrieve",
|
||||||
|
Key = key,
|
||||||
|
PerformedBy = user,
|
||||||
|
Timestamp = DateTime.UtcNow
|
||||||
|
});
|
||||||
|
_db.SaveChanges();
|
||||||
|
|
||||||
|
return Encoding.UTF8.GetString(decrypted);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal async Task<bool> DeleteAsync(string tenantId, string key, string user)
|
||||||
|
{
|
||||||
|
var model = _db.Secrets
|
||||||
|
.Where(s => s.TenantId == tenantId && s.Key == key)
|
||||||
|
.OrderByDescending(x => x.CreatedAt)
|
||||||
|
.FirstOrDefault();
|
||||||
|
|
||||||
|
if (model == null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
_db.Secrets.Remove(model);
|
||||||
|
_db.AuditLogs.Add(new AuditLog
|
||||||
|
{
|
||||||
|
TenantId = tenantId,
|
||||||
|
Action = "Delete",
|
||||||
|
Key = key,
|
||||||
|
PerformedBy = user,
|
||||||
|
Timestamp = DateTime.UtcNow
|
||||||
|
});
|
||||||
|
await _db.SaveChangesAsync();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Binary file not shown.
After Width: | Height: | Size: 88 KiB |
213
LICENSE
213
LICENSE
|
@ -1,73 +1,204 @@
|
||||||
Apache License
|
|
||||||
Version 2.0, January 2004
|
|
||||||
http://www.apache.org/licenses/
|
|
||||||
|
|
||||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
https://EonaCat.com/license/
|
||||||
|
|
||||||
1. Definitions.
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
OF SOFTWARE BY EONACAT (JEROEN SAEY)
|
||||||
|
|
||||||
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
1. Definitions.
|
||||||
|
|
||||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
APPENDIX: How to apply the Apache License to your work.
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
Copyright 2025 EonaCat
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
Copyright [yyyy] [name of copyright owner]
|
||||||
you may not use this file except in compliance with the License.
|
|
||||||
You may obtain a copy of the License at
|
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
Unless required by applicable law or agreed to in writing, software
|
||||||
See the License for the specific language governing permissions and
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
limitations under the License.
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
|
|
282
README.md
282
README.md
|
@ -1,3 +1,283 @@
|
||||||
|
|
||||||
|
|
||||||
# EonaCat.SecretVault
|
# EonaCat.SecretVault
|
||||||
|
|
||||||
EonaCat.SecretVault
|
------------
|
||||||
|
|
||||||
|
Generate a secure vault for storing secrets like API keys, passwords, and other sensitive information.
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
EonaCat.SecretVault is a secure multi-tenant offline vault for storing secrets using AES encryption and SQLite, protected with API key authentication and per-tenant encryption keys.
|
||||||
|
It consists of a server that manages the storage and retrieval of secrets, and a client library that allows you to interact with the server.
|
||||||
|
The server provides a RESTful API for storing and retrieving secrets, while the client library simplifies the interaction with the server.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
- Secure storage of secrets
|
||||||
|
- RESTful API for storing and retrieving secrets
|
||||||
|
- Client library for easy interaction with the server
|
||||||
|
- Multi-tenancy support
|
||||||
|
- Supports HMAC authentication for secure access
|
||||||
|
- Supports SQLite for data storage
|
||||||
|
- Audit logging
|
||||||
|
- Cross-platform compatibility
|
||||||
|
- Easy to use
|
||||||
|
- Open-source and free to use
|
||||||
|
|
||||||
|
# Extra security notices:
|
||||||
|
- Rotate your API keys regularly.
|
||||||
|
- Use strong, unique API keys for each tenant.
|
||||||
|
- Ensure your `ROOT_PROTECTOR_KEY` is kept secret and secure.
|
||||||
|
- Rotate the `ROOT_PROTECTOR_KEY` if you suspect it has been compromised.
|
||||||
|
- Use HTTPS to encrypt data in transit.
|
||||||
|
|
||||||
|
### API Keys
|
||||||
|
|
||||||
|
- API keys are generated as secure random 256-bit strings.
|
||||||
|
- Only SHA256 hashes of API keys are stored in the database.
|
||||||
|
- Incoming API keys are hashed and compared against stored hashes for authentication.
|
||||||
|
|
||||||
|
### Per-Tenant Encryption Keys
|
||||||
|
|
||||||
|
- Each tenant has a unique 256-bit AES key, encrypted at rest with a master root key (`ROOT_PROTECTOR_KEY`).
|
||||||
|
- Tenant keys are decrypted only in-memory during operations.
|
||||||
|
|
||||||
|
## 🧩 Multi-Tenant Support
|
||||||
|
Each API key is tied to a unique tenant.
|
||||||
|
Secrets stored by one tenant cannot be retrieved by another.
|
||||||
|
|
||||||
|
Tenant mapping is defined in the TenantApiKey table:
|
||||||
|
|
||||||
|
ApiKey TenantId
|
||||||
|
abc123-myapikey tenant-001
|
||||||
|
def456-otherkey tenant-002
|
||||||
|
|
||||||
|
## 🔍 Audit Logs
|
||||||
|
|
||||||
|
Every secret operation is logged in the AuditLogs table:
|
||||||
|
|
||||||
|
Id TenantId Action Key PerformedBy Timestamp
|
||||||
|
1 tenant-001 Store db-password apikey-user 2025-07-06 17:23:54
|
||||||
|
2 tenant-001 Retrieve db-password apikey-user 2025-07-06 17:25:04
|
||||||
|
|
||||||
|
|
||||||
|
HMAC Integrity (Optional)
|
||||||
|
The server computes HMAC-SHA256 for internal verification.
|
||||||
|
|
||||||
|
You can expand this to validate incoming payloads by signing client-side with:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
var hmac = new HMACSHA256(Convert.FromBase64String(masterKey));
|
||||||
|
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(content));
|
||||||
|
```
|
||||||
|
|
||||||
|
### Environment Variables
|
||||||
|
|
||||||
|
- `ROOT_PROTECTOR_KEY`: Base64-encoded 256-bit key to encrypt tenant keys.
|
||||||
|
|
||||||
|
### Example of ROOT_PROTECTOR_KEY:
|
||||||
|
```bash
|
||||||
|
export ROOT_PROTECTOR_KEY="your-base64-encoded-256-bit-key"
|
||||||
|
```
|
||||||
|
|
||||||
|
e.g.:
|
||||||
|
```bash
|
||||||
|
export ROOT_PROTECTOR_KEY="c2VjcmV0cGFzc3dvcmQtbm90LXN0b3JlLWluLWRpc3BsYXktb3V0c2lkZS1lbnZpcm9ubWVudC1rZXktdG8tYmUtdXNlZC1mb3ItZW5jcnlwdGlvbi1rZXktZm9yLXNlY3JldC1zdG9yYWdl"
|
||||||
|
```
|
||||||
|
|
||||||
|
EonaCat.SecretVault.Client library
|
||||||
|
|
||||||
|
## How to use the client:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
using EonaCat.SecretVault.Client;
|
||||||
|
|
||||||
|
var vault = new SecretVaultClient("https://your-vault-url.com/", "your-api-key");
|
||||||
|
|
||||||
|
// Store a secret
|
||||||
|
await vault.StoreAsync("db-password", "S3cr3t!");
|
||||||
|
|
||||||
|
// Retrieve a secret
|
||||||
|
string? secret = await vault.RetrieveAsync("db-password");
|
||||||
|
Console.WriteLine($"Secret: {secret}");
|
||||||
|
|
||||||
|
// Delete a secret
|
||||||
|
await vault.DeleteAsync("db-password");
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
## How to use the server:
|
||||||
|
|
||||||
|
## Generating a new tenant:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
|
||||||
|
string GenerateApiKey()
|
||||||
|
{
|
||||||
|
return Convert.ToBase64String(RandomNumberGenerator.GetBytes(32));
|
||||||
|
}
|
||||||
|
|
||||||
|
string HashApiKey(string apiKey)
|
||||||
|
{
|
||||||
|
using var sha256 = SHA256.Create();
|
||||||
|
var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(apiKey));
|
||||||
|
return Convert.ToBase64String(hash);
|
||||||
|
}
|
||||||
|
|
||||||
|
var rootKey = Environment.GetEnvironmentVariable("ROOT_PROTECTOR_KEY")!;
|
||||||
|
var tenantKey = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32));
|
||||||
|
|
||||||
|
var encryptedTenantKey = TenantKeyProtector.EncryptTenantKey(tenantKey, rootKey);
|
||||||
|
var apiKey = GenerateApiKey();
|
||||||
|
var apiKeyHash = HashApiKey(apiKey);
|
||||||
|
|
||||||
|
_db.ApiKeys.Add(new TenantApiKey
|
||||||
|
{
|
||||||
|
ApiKey = newApiKey,
|
||||||
|
TenantId = "tenant-003",
|
||||||
|
EncryptionKey = newTenantKey,
|
||||||
|
EncryptedTenantKey = encryptedTenantKey,
|
||||||
|
ApiKeyHash = apiKeyHash
|
||||||
|
});
|
||||||
|
await _db.SaveChangesAsync();
|
||||||
|
```
|
||||||
|
### Edit appsettings.json or use environment variables if needed (default uses SQLite):
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"ConnectionStrings": {
|
||||||
|
"Default": "Data Source=EonaCatSecretVault.db"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Api usage:
|
||||||
|
Base URL: http://localhost:5000/api/secrets
|
||||||
|
All requests must include:
|
||||||
|
- `X-Api-Key` header with your API key
|
||||||
|
|
||||||
|
## Generate a new tenant:
|
||||||
|
|
||||||
|
POST /api/admin/generate-key?role=ReadWrite
|
||||||
|
|
||||||
|
```http
|
||||||
|
Headers:
|
||||||
|
X-Api-Key: abc123-myapikey
|
||||||
|
### Response:
|
||||||
|
HTTP/1.1 200
|
||||||
|
Body:
|
||||||
|
{
|
||||||
|
"apiKey": "qY6LZ5i1dNpsQFF2kLE7uUd8Md5FeKfMY5r6KfzH7i8=",
|
||||||
|
"role": "ReadWrite"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Revoke an API key:
|
||||||
|
|
||||||
|
DELETE /api/admin/revoke-key?key=abc123-myapikey
|
||||||
|
```http
|
||||||
|
Headers:
|
||||||
|
X-Api-Key: abc123-myapikey
|
||||||
|
```
|
||||||
|
|
||||||
|
### Response:
|
||||||
|
```http
|
||||||
|
HTTP/1.1 200 OK
|
||||||
|
Body:
|
||||||
|
"Key revoked"
|
||||||
|
```
|
||||||
|
|
||||||
|
## List all API keys:
|
||||||
|
GET /api/admin/keys
|
||||||
|
```http
|
||||||
|
Headers:
|
||||||
|
X-Api-Key: abc123-myapikey
|
||||||
|
```
|
||||||
|
|
||||||
|
### Response:
|
||||||
|
```http
|
||||||
|
HTTP/1.1 200 OK
|
||||||
|
Body:
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"apiKey": "qY6LZ5i1dNpsQFF2kLE7uUd8Md5FeKfMY5r6KfzH7i8=",
|
||||||
|
"role": "ReadWrite",
|
||||||
|
"isActive": true,
|
||||||
|
"createdAt": "2025-07-06T17:00:00Z"
|
||||||
|
},
|
||||||
|
...
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Store a secret:
|
||||||
|
|
||||||
|
POST /api/secrets/store?key=my-service-token
|
||||||
|
|
||||||
|
```http
|
||||||
|
Headers:
|
||||||
|
Content-Type: application/json
|
||||||
|
X-Api-Key: abc123-myapikey
|
||||||
|
```
|
||||||
|
|
||||||
|
### Response:
|
||||||
|
```http
|
||||||
|
HTTP/1.1 200 OK
|
||||||
|
```
|
||||||
|
|
||||||
|
## Retrieve a secret:
|
||||||
|
GET /api/secrets/retrieve?key=my-service-token
|
||||||
|
```http
|
||||||
|
Headers:
|
||||||
|
X-Api-Key: abc123-myapikey
|
||||||
|
```
|
||||||
|
|
||||||
|
### Response:
|
||||||
|
```http
|
||||||
|
HTTP/1.1 200 OK
|
||||||
|
Body:
|
||||||
|
"super-secret-value"
|
||||||
|
```
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
using EonaCat.SecretVault.Data;
|
||||||
|
using EonaCat.SecretVault.Middleware;
|
||||||
|
using EonaCat.SecretVault.Services;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using System;
|
||||||
|
|
||||||
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
|
var config = builder.Configuration;
|
||||||
|
|
||||||
|
builder.Services.AddDbContext<SecretDbContext>(x => x.UseSqlite("Data Source=EonaCatSecretVault.db"));
|
||||||
|
builder.Services.AddScoped<SecretService>();
|
||||||
|
builder.Services.AddScoped<TenantKeyService>();
|
||||||
|
builder.Services.AddControllers();
|
||||||
|
|
||||||
|
var app = builder.Build();
|
||||||
|
|
||||||
|
app.UseHsts();
|
||||||
|
app.UseHttpsRedirection();
|
||||||
|
app.UseMiddleware<ApiKeyMiddleware>();
|
||||||
|
app.MapControllers();
|
||||||
|
|
||||||
|
using (var scope = app.Services.CreateScope())
|
||||||
|
{
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<SecretDbContext>();
|
||||||
|
db.Database.EnsureCreated();
|
||||||
|
}
|
||||||
|
|
||||||
|
app.Run();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Curl Example:
|
||||||
|
|
||||||
|
```curl
|
||||||
|
curl -X POST http://localhost:5000/api/secrets/store?key=MYKEY \
|
||||||
|
-H "X-Api-Key: abc123-myapikey" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d "\"sensitive-data\""
|
||||||
|
|
||||||
|
curl http://localhost:5000/api/secrets/retrieve?key=MYKEY \
|
||||||
|
-H "X-Api-Key: abc123-myapikey"
|
||||||
|
```
|
Loading…
Reference in New Issue