Skip to content

Commit

Permalink
f
Browse files Browse the repository at this point in the history
  • Loading branch information
pawelvds committed Jan 29, 2024
1 parent f8992d0 commit 2119715
Showing 1 changed file with 69 additions and 31 deletions.
100 changes: 69 additions & 31 deletions src/fiskaltrust.Launcher/Commands/Common.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,19 @@ public CommonCommand(string name, bool addCliOnlyParameters = true) : base(name)

if (addCliOnlyParameters)
{
AddOption(new Option<string>("--launcher-configuration-file", getDefaultValue: () => Paths.LauncherConfigurationFileName));
AddOption(new Option<string>("--legacy-configuration-file", getDefaultValue: () => Paths.LegacyConfigurationFileName));
AddOption(new Option<string>("--launcher-configuration-file",
getDefaultValue: () => Paths.LauncherConfigurationFileName));
AddOption(new Option<string>("--legacy-configuration-file",
getDefaultValue: () => Paths.LegacyConfigurationFileName));
AddOption(new Option<bool>("--merge-legacy-config-if-exists", getDefaultValue: () => true));
}
}
}

public class CommonOptions
{
public CommonOptions(LauncherConfiguration argsLauncherConfiguration, string launcherConfigurationFile, string legacyConfigurationFile, bool mergeLegacyConfigIfExists)
public CommonOptions(LauncherConfiguration argsLauncherConfiguration, string launcherConfigurationFile,
string legacyConfigurationFile, bool mergeLegacyConfigIfExists)
{
ArgsLauncherConfiguration = argsLauncherConfiguration;
LauncherConfigurationFile = launcherConfigurationFile;
Expand All @@ -62,7 +65,9 @@ public CommonOptions(LauncherConfiguration argsLauncherConfiguration, string lau

public record CommonProperties
{
public CommonProperties(LauncherConfiguration launcherConfiguration, ftCashBoxConfiguration cashboxConfiguration, ECDiffieHellman clientEcdh, IDataProtectionProvider dataProtectionProvider)
public CommonProperties(LauncherConfiguration launcherConfiguration,
ftCashBoxConfiguration cashboxConfiguration, ECDiffieHellman clientEcdh,
IDataProtectionProvider dataProtectionProvider)
{
LauncherConfiguration = launcherConfiguration;
CashboxConfiguration = cashboxConfiguration;
Expand Down Expand Up @@ -96,23 +101,28 @@ public static async Task<int> HandleAsync<O, S>(
try
{
options.LauncherConfigurationFile = Path.GetFullPath(options.LauncherConfigurationFile);
launcherConfiguration = LauncherConfiguration.Deserialize(await File.ReadAllTextAsync(options.LauncherConfigurationFile));
launcherConfiguration =
LauncherConfiguration.Deserialize(await File.ReadAllTextAsync(options.LauncherConfigurationFile));
}
catch (Exception e)
{
if (!(options.MergeLegacyConfigIfExists && File.Exists(options.LegacyConfigurationFile)))
{
if (File.Exists(options.LauncherConfigurationFile))
{
Log.Warning(e, "Could not parse launcher configuration file \"{LauncherConfigurationFile}\".", options.LauncherConfigurationFile);
Log.Warning(e, "Could not parse launcher configuration file \"{LauncherConfigurationFile}\".",
options.LauncherConfigurationFile);
}
else
{
Log.Warning("Launcher configuration file \"{LauncherConfigurationFile}\" does not exist.", options.LauncherConfigurationFile);
Log.Warning("Launcher configuration file \"{LauncherConfigurationFile}\" does not exist.",
options.LauncherConfigurationFile);
}

Log.Warning("Using command line parameters only.", options.LauncherConfigurationFile);
}
}

Log.Verbose("Merging legacy launcher config file.");
if (options.MergeLegacyConfigIfExists && File.Exists(options.LegacyConfigurationFile))
{
Expand All @@ -136,7 +146,8 @@ public static async Task<int> HandleAsync<O, S>(
launcherConfiguration.OverwriteWith(options.ArgsLauncherConfiguration);
await EnsureServiceDirectoryExists(launcherConfiguration);

if (!launcherConfiguration.UseOffline!.Value && (launcherConfiguration.CashboxId is null || launcherConfiguration.AccessToken is null))
if (!launcherConfiguration.UseOffline!.Value &&
(launcherConfiguration.CashboxId is null || launcherConfiguration.AccessToken is null))
{
Log.Error("CashBoxId and AccessToken are not provided.");
}
Expand All @@ -157,7 +168,8 @@ public static async Task<int> HandleAsync<O, S>(
ECDiffieHellman? clientEcdh = null;
try
{
clientEcdh = await LoadCurve(launcherConfiguration.CashboxId!.Value, launcherConfiguration.AccessToken!, launcherConfiguration.ServiceFolder!, launcherConfiguration.UseOffline!.Value);
clientEcdh = await LoadCurve(launcherConfiguration.CashboxId!.Value, launcherConfiguration.AccessToken!,
launcherConfiguration.ServiceFolder!, launcherConfiguration.UseOffline!.Value);
}
catch (Exception e)
{
Expand All @@ -179,19 +191,23 @@ public static async Task<int> HandleAsync<O, S>(
catch (Exception e)
{
var message = "Could not download Cashbox configuration. ";
message += $"(Launcher is running in {(launcherConfiguration.Sandbox!.Value ? "sandbox" : "production")} mode.";
message +=
$"(Launcher is running in {(launcherConfiguration.Sandbox!.Value ? "sandbox" : "production")} mode.";
if (!launcherConfiguration.Sandbox!.Value)
{
message += " Did you forget the --sandbox flag?";
}

message += ")";
Log.Error(e, message);
}

try
{
var cashboxConfigurationFile = launcherConfiguration.CashboxConfigurationFile!;
launcherConfiguration.OverwriteWith(LauncherConfigurationInCashBoxConfiguration.Deserialize(await File.ReadAllTextAsync(cashboxConfigurationFile)));
launcherConfiguration.OverwriteWith(
LauncherConfigurationInCashBoxConfiguration.Deserialize(
await File.ReadAllTextAsync(cashboxConfigurationFile)));
}
catch (Exception e)
{
Expand All @@ -202,8 +218,13 @@ public static async Task<int> HandleAsync<O, S>(
var cashboxConfiguration = new ftCashBoxConfiguration();
try
{
cashboxConfiguration = CashBoxConfigurationExt.Deserialize(await File.ReadAllTextAsync(launcherConfiguration.CashboxConfigurationFile!));
if (clientEcdh is not null) { cashboxConfiguration.Decrypt(launcherConfiguration, clientEcdh); }
cashboxConfiguration =
CashBoxConfigurationExt.Deserialize(
await File.ReadAllTextAsync(launcherConfiguration.CashboxConfigurationFile!));
if (clientEcdh is not null)
{
cashboxConfiguration.Decrypt(launcherConfiguration, clientEcdh);
}
}
catch (Exception e)
{
Expand All @@ -214,7 +235,8 @@ public static async Task<int> HandleAsync<O, S>(
// Previous log messages will be logged here using this logger.
Log.Logger = new LoggerConfiguration()
.AddLoggingConfiguration(launcherConfiguration)
.AddFileLoggingConfiguration(launcherConfiguration, new[] { "fiskaltrust.Launcher", launcherConfiguration.CashboxId?.ToString() })
.AddFileLoggingConfiguration(launcherConfiguration,
new[] { "fiskaltrust.Launcher", launcherConfiguration.CashboxId?.ToString() })
.Enrich.FromLogContext()
.CreateLogger();

Expand All @@ -232,23 +254,29 @@ public static async Task<int> HandleAsync<O, S>(
}

Log.Debug("Launcher Configuration File: {LauncherConfigurationFile}", options.LauncherConfigurationFile);
Log.Debug("Cashbox Configuration File: {CashboxConfigurationFile}", launcherConfiguration.CashboxConfigurationFile);
Log.Debug("Cashbox Configuration File: {CashboxConfigurationFile}",
launcherConfiguration.CashboxConfigurationFile);
Log.Debug("Launcher Configuration: {@LauncherConfiguration}", launcherConfiguration.Redacted());

Log.Debug("Launcher running as {ServiceType}", Enum.GetName(typeof(ServiceTypes), host.Services.GetRequiredService<ServiceType>().Type));
Log.Debug("Launcher running as {ServiceType}",
Enum.GetName(typeof(ServiceTypes), host.Services.GetRequiredService<ServiceType>().Type));

var dataProtectionProvider = DataProtectionExtensions.Create(launcherConfiguration.AccessToken, useFallback: launcherConfiguration.UseLegacyDataProtection!.Value);
var dataProtectionProvider = DataProtectionExtensions.Create(launcherConfiguration.AccessToken,
useFallback: launcherConfiguration.UseLegacyDataProtection!.Value);

try
{
launcherConfiguration.Decrypt(dataProtectionProvider.CreateProtector(LauncherConfiguration.DATA_PROTECTION_DATA_PURPOSE));
launcherConfiguration.Decrypt(
dataProtectionProvider.CreateProtector(LauncherConfiguration.DATA_PROTECTION_DATA_PURPOSE));
}
catch (Exception e)
{
Log.Warning(e, "Error decrypring launcher configuration file.");
}

return await handler(options, new CommonProperties(launcherConfiguration, cashboxConfiguration, clientEcdh!, dataProtectionProvider), specificOptions, host.Services.GetRequiredService<S>());
return await handler(options,
new CommonProperties(launcherConfiguration, cashboxConfiguration, clientEcdh!, dataProtectionProvider),
specificOptions, host.Services.GetRequiredService<S>());
}

private static async Task EnsureServiceDirectoryExists(LauncherConfiguration config)
Expand All @@ -260,26 +288,30 @@ private static async Task EnsureServiceDirectoryExists(LauncherConfiguration con
{
Directory.CreateDirectory(serviceDirectory);

if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ||
RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
var user = Environment.GetEnvironmentVariable("USER");
if (!string.IsNullOrEmpty(user))
{
var chownResult = await ProcessHelper.RunProcess("chown", new[] { user, serviceDirectory }, LogEventLevel.Debug);
var chownResult = await ProcessHelper.RunProcess("chown", new[] { user, serviceDirectory },
LogEventLevel.Debug);
if (chownResult.exitCode != 0)
{
Log.Warning("Failed to change owner of the service directory.");
}

var chmodResult = await ProcessHelper.RunProcess("chmod", new[] { "774", serviceDirectory }, LogEventLevel.Debug);
var chmodResult = await ProcessHelper.RunProcess("chmod", new[] { "774", serviceDirectory },
LogEventLevel.Debug);
if (chmodResult.exitCode != 0)
{
Log.Warning("Failed to change permissions of the service directory.");
}
}
else
{
Log.Warning("Service user name is not set. Owner of the service directory will not be changed.");
Log.Warning(
"Service user name is not set. Owner of the service directory will not be changed.");
}
}
else
Expand All @@ -291,21 +323,26 @@ private static async Task EnsureServiceDirectoryExists(LauncherConfiguration con
catch (UnauthorizedAccessException e)
{
// will exit with non-zero exit code later.
Log.Fatal(e, "Access to the path '{ServiceDirectory}' is denied. Please run the application with sufficient permissions.", serviceDirectory);
Log.Fatal(e,
"Access to the path '{ServiceDirectory}' is denied. Please run the application with sufficient permissions.",
serviceDirectory);
}
}

public static async Task<ECDiffieHellman> LoadCurve(Guid cashboxId, string accessToken, string serviceFolder, bool useOffline = false, bool dryRun = false, bool useFallback = false)
public static async Task<ECDiffieHellman> LoadCurve(Guid cashboxId, string accessToken, string serviceFolder,
bool useOffline = false, bool dryRun = false, bool useFallback = false)
{
Log.Verbose("Loading Curve.");
var dataProtector = DataProtectionExtensions.Create(accessToken, useFallback: useFallback).CreateProtector(CashBoxConfigurationExt.DATA_PROTECTION_DATA_PURPOSE);
var dataProtector = DataProtectionExtensions.Create(accessToken, useFallback: useFallback)
.CreateProtector(CashBoxConfigurationExt.DATA_PROTECTION_DATA_PURPOSE);
var clientEcdhPath = Path.Combine(serviceFolder, $"client-{cashboxId}.ecdh");

if (File.Exists(clientEcdhPath))
{
try
{
return ECDiffieHellmanExt.Deserialize(dataProtector.Unprotect(await File.ReadAllTextAsync(clientEcdhPath)));
return ECDiffieHellmanExt.Deserialize(
dataProtector.Unprotect(await File.ReadAllTextAsync(clientEcdhPath)));
}
catch (Exception e)
{
Expand All @@ -322,7 +359,9 @@ public static async Task<ECDiffieHellman> LoadCurve(Guid cashboxId, string acces
{
File.Delete(offlineClientEcdhPath);
}
catch { }
catch
{
}

return clientEcdh;
}
Expand All @@ -334,8 +373,7 @@ public static async Task<ECDiffieHellman> LoadCurve(Guid cashboxId, string acces
await File.WriteAllTextAsync(clientEcdhPath, dataProtector.Protect(newClientEcdh.Serialize()));
}

return clientEcdh;
}
return clientEcdh;
}
}
}
}

0 comments on commit 2119715

Please sign in to comment.