Provision US-16 dependencies credentials HTTPS and native service configurations
This commit is contained in:
1 parent
950f67d8b7
commit
eedf2a941b
34 files changed
+1703
-373
No files matched your search
@@ -0,0 +1,72 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.RegularExpressions;
|
||||
using Npgsql;
|
||||
|
||||
namespace HealthApp.Provisioning;
|
||||
|
||||
public static class DatabaseProvisioning
|
||||
{
|
||||
public static async Task Create(string serviceDirectory, string? adminFile)
|
||||
{
|
||||
var service = Deployment.ReadService(serviceDirectory);
|
||||
var database = service.Database ?? throw new InvalidOperationException("This service owns no database.");
|
||||
if (!Regex.IsMatch(database.Name, "^[a-z][a-z0-9_]{1,62}$") || !Regex.IsMatch(database.User, "^[a-z][a-z0-9_]{1,62}$") ||
|
||||
!Regex.IsMatch(database.Password, "^[A-F0-9]{64}$")) throw new InvalidOperationException("Generated database settings are invalid.");
|
||||
var adminConnection = adminFile is null ? null : File.ReadAllText(adminFile).Trim();
|
||||
async Task<string> Sql(string sql, string target = "postgres")
|
||||
{
|
||||
if (adminConnection is not null)
|
||||
{
|
||||
var settings = new NpgsqlConnectionStringBuilder(adminConnection) { Database = target, Pooling = false };
|
||||
await using var connection = new NpgsqlConnection(settings.ConnectionString);
|
||||
await connection.OpenAsync();
|
||||
await using var command = new NpgsqlCommand(sql, connection);
|
||||
var result = await command.ExecuteScalarAsync();
|
||||
return result?.ToString() ?? "";
|
||||
}
|
||||
var start = new ProcessStartInfo("runuser") { RedirectStandardInput = true, RedirectStandardOutput = true,
|
||||
RedirectStandardError = true, UseShellExecute = false };
|
||||
foreach (var argument in new[] { "-u", "postgres", "--", "psql", "--no-psqlrc", "--set=ON_ERROR_STOP=1", "--tuples-only", "--no-align", "--dbname", target })
|
||||
start.ArgumentList.Add(argument);
|
||||
using var process = Process.Start(start) ?? throw new InvalidOperationException("Could not run PostgreSQL administration.");
|
||||
var stdout = process.StandardOutput.ReadToEndAsync();
|
||||
var stderr = process.StandardError.ReadToEndAsync();
|
||||
await process.StandardInput.WriteAsync(sql);
|
||||
process.StandardInput.Close();
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
|
||||
try { await process.WaitForExitAsync(timeout.Token); }
|
||||
catch (OperationCanceledException) { process.Kill(true); throw; }
|
||||
await stderr; // Never print SQL or passwords, including PostgreSQL error echoes.
|
||||
if (process.ExitCode != 0) throw new InvalidOperationException("PostgreSQL administration failed; existing data was retained.");
|
||||
return (await stdout).Trim();
|
||||
}
|
||||
static bool True(string value) => value is "t" or "True";
|
||||
var userExists = True(await Sql($"SELECT EXISTS(SELECT FROM pg_roles WHERE rolname='{database.User}');"));
|
||||
if (!userExists)
|
||||
await Sql($"CREATE ROLE {database.User} LOGIN PASSWORD '{database.Password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION;");
|
||||
var exists = True(await Sql($"SELECT EXISTS(SELECT FROM pg_database WHERE datname='{database.Name}');"));
|
||||
if (exists && !True(await Sql($"SELECT pg_get_userbyid(datdba)='{database.User}' FROM pg_database WHERE datname='{database.Name}';")))
|
||||
throw new InvalidOperationException("Existing database has another owner; it was not changed.");
|
||||
if (!exists) await Sql($"CREATE DATABASE {database.Name} OWNER {database.User};");
|
||||
await Sql($"REVOKE ALL ON DATABASE {database.Name} FROM PUBLIC;");
|
||||
await Sql($"REVOKE ALL ON SCHEMA public FROM PUBLIC; ALTER SCHEMA public OWNER TO {database.User}; GRANT USAGE, CREATE ON SCHEMA public TO {database.User};", database.Name);
|
||||
// With an external PostgreSQL admin connection, preserve that endpoint in generated application config.
|
||||
if (adminConnection is not null)
|
||||
{
|
||||
var admin = new NpgsqlConnectionStringBuilder(adminConnection);
|
||||
database = database with { Host = admin.Host!, Port = admin.Port };
|
||||
service = service with { Database = database };
|
||||
var key = service.Name == "patient-profile" ? "ConnectionStrings__PatientDatabase" : "ConnectionStrings__ObservationDatabase";
|
||||
service.Environment[key] = Deployment.ConnectionString(database);
|
||||
File.WriteAllText(Path.Combine(serviceDirectory, "service.json"), System.Text.Json.JsonSerializer.Serialize(service, Deployment.Json));
|
||||
}
|
||||
await Check(database);
|
||||
}
|
||||
public static async Task Check(DatabaseSettings database)
|
||||
{
|
||||
await using var connection = new NpgsqlConnection(Deployment.ConnectionString(database));
|
||||
await connection.OpenAsync();
|
||||
await using var command = new NpgsqlCommand("SELECT current_user", connection);
|
||||
if ((string?)await command.ExecuteScalarAsync() != database.User) throw new InvalidOperationException("Database service identity does not match.");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user