Skip to content

Commit

Permalink
feat(postgres): connect with ssl
Browse files Browse the repository at this point in the history
  • Loading branch information
pogromistik committed Jun 19, 2024
1 parent 614bb38 commit 47acf3b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
12 changes: 12 additions & 0 deletions src/Sitko.Core.App/Helpers/CertHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace Sitko.Core.App.Helpers;

public static class CertHelper
{
public static string GetCertPath(string sslCertBase64)
{
var cert = Convert.FromBase64String(sslCertBase64);
var path = Path.GetTempFileName();
File.WriteAllBytes(path, cert);
return path;
}
}
15 changes: 14 additions & 1 deletion src/Sitko.Core.Db.Postgres/PostgresDatabaseModuleConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Microsoft.Extensions.DependencyInjection;
using Npgsql;
using Sitko.Core.App;
using Sitko.Core.App.Helpers;

namespace Sitko.Core.Db.Postgres;

Expand All @@ -15,6 +16,8 @@ public class PostgresDatabaseModuleOptions<TDbContext> : BaseDbModuleOptions<TDb
public int Port { get; set; } = 5432;
public string Username { get; set; } = "postgres";
public string Password { get; set; } = string.Empty;
public SslMode SslMode { get; set; } = SslMode.Disable;
public string? SaslCertBase64 { get; set; }
public bool EnableNpgsqlPooling { get; set; } = true;
[JsonIgnore] public Assembly? MigrationsAssembly { get; set; }
public bool AutoApplyMigrations { get; set; } = true;
Expand All @@ -38,9 +41,18 @@ public NpgsqlConnectionStringBuilder CreateBuilder()
Password = Password,
Database = Database,
Pooling = EnableNpgsqlPooling,
IncludeErrorDetail = IncludeErrorDetails
IncludeErrorDetail = IncludeErrorDetails,
SslMode = SslMode
};

switch (SslMode)
{
case SslMode.VerifyFull:
case SslMode.VerifyCA:
connBuilder.RootCertificate = CertHelper.GetCertPath(SaslCertBase64!);
break;
}

foreach (var (key, value) in ConnectionOptions)
{
try
Expand Down Expand Up @@ -68,6 +80,7 @@ public PostgresDatabaseModuleOptionsValidator()
RuleFor(o => o.Username).NotEmpty().WithMessage("Postgres username is empty");
RuleFor(o => o.Database).NotEmpty().WithMessage("Postgres database is empty");
RuleFor(o => o.Port).GreaterThan(0).WithMessage("Postgres port is empty");
RuleFor(o => o.SaslCertBase64).NotEmpty().When(o => o.SslMode is SslMode.VerifyFull or SslMode.VerifyCA).WithMessage("Ssl cert base64 is empty");
}
}

0 comments on commit 47acf3b

Please sign in to comment.