Skip to content

Commit

Permalink
changes
Browse files Browse the repository at this point in the history
  • Loading branch information
pawelvds committed Jan 29, 2024
1 parent 779982b commit 2c3d294
Showing 1 changed file with 122 additions and 126 deletions.
248 changes: 122 additions & 126 deletions src/fiskaltrust.Launcher/Commands/Common.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,69 +17,64 @@
using Serilog;
using Serilog.Events;

namespace fiskaltrust.Launcher.Commands;

public record SubArguments(IEnumerable<string> Args);

public class CommonCommand : Command
namespace fiskaltrust.Launcher.Commands
{
public CommonCommand(string name, bool addCliOnlyParameters = true) : base(name)
public record SubArguments(IEnumerable<string> Args);

public class CommonCommand : Command
{
AddOption(new Option<Guid?>("--cashbox-id"));
AddOption(new Option<string?>("--access-token"));
AddOption(new Option<bool>("--sandbox"));
AddOption(new Option<string?>("--log-folder"));
public CommonCommand(string name, bool addCliOnlyParameters = true) : base(name)
{
AddOption(new Option<Guid?>("--cashbox-id"));
AddOption(new Option<string?>("--access-token"));
AddOption(new Option<bool>("--sandbox"));
AddOption(new Option<string?>("--log-folder"));

var logLevelOption = new Option<LogLevel?>("--log-level", "Set the log level of the application.");
logLevelOption.AddAlias("-v");
logLevelOption.AddAlias("--verbosity");
AddOption(logLevelOption);
var logLevelOption = new Option<LogLevel?>("--log-level", "Set the log level of the application.");
logLevelOption.AddAlias("-v");
logLevelOption.AddAlias("--verbosity");
AddOption(logLevelOption);

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

public class CommonOptions
{
public CommonOptions(LauncherConfiguration argsLauncherConfiguration, string launcherConfigurationFile,
string legacyConfigurationFile, bool mergeLegacyConfigIfExists)
public class CommonOptions
{
ArgsLauncherConfiguration = argsLauncherConfiguration;
LauncherConfigurationFile = launcherConfigurationFile;
LegacyConfigurationFile = legacyConfigurationFile;
MergeLegacyConfigIfExists = mergeLegacyConfigIfExists;
}
public CommonOptions(LauncherConfiguration argsLauncherConfiguration, string launcherConfigurationFile, string legacyConfigurationFile, bool mergeLegacyConfigIfExists)
{
ArgsLauncherConfiguration = argsLauncherConfiguration;
LauncherConfigurationFile = launcherConfigurationFile;
LegacyConfigurationFile = legacyConfigurationFile;
MergeLegacyConfigIfExists = mergeLegacyConfigIfExists;
}

public LauncherConfiguration ArgsLauncherConfiguration { get; set; }
public string LauncherConfigurationFile { get; set; }
public string LegacyConfigurationFile { get; set; }
public bool MergeLegacyConfigIfExists { get; set; }
}
public LauncherConfiguration ArgsLauncherConfiguration { get; set; }
public string LauncherConfigurationFile { get; set; }
public string LegacyConfigurationFile { get; set; }
public bool MergeLegacyConfigIfExists { get; set; }
}

public record CommonProperties
{
public CommonProperties(LauncherConfiguration launcherConfiguration,
ftCashBoxConfiguration cashboxConfiguration, ECDiffieHellman clientEcdh,
IDataProtectionProvider dataProtectionProvider)
public record CommonProperties
{
LauncherConfiguration = launcherConfiguration;
CashboxConfiguration = cashboxConfiguration;
ClientEcdh = clientEcdh;
DataProtectionProvider = dataProtectionProvider;
}
public CommonProperties(LauncherConfiguration launcherConfiguration, ftCashBoxConfiguration cashboxConfiguration, ECDiffieHellman clientEcdh, IDataProtectionProvider dataProtectionProvider)
{
LauncherConfiguration = launcherConfiguration;
CashboxConfiguration = cashboxConfiguration;
ClientEcdh = clientEcdh;
DataProtectionProvider = dataProtectionProvider;
}

public LauncherConfiguration LauncherConfiguration { get; set; }
public ftCashBoxConfiguration CashboxConfiguration { get; set; }
public ECDiffieHellman ClientEcdh { get; set; }
public IDataProtectionProvider DataProtectionProvider { get; set; }
}
public LauncherConfiguration LauncherConfiguration { get; set; }
public ftCashBoxConfiguration CashboxConfiguration { get; set; }
public ECDiffieHellman ClientEcdh { get; set; }
public IDataProtectionProvider DataProtectionProvider { get; set; }
}

public static class CommonHandler
{
Expand All @@ -97,43 +92,45 @@ public static async Task<int> HandleAsync<O, S>(

var launcherConfiguration = new LauncherConfiguration();

Log.Verbose("Reading launcher config file.");
try
{
options.LauncherConfigurationFile = Path.GetFullPath(options.LauncherConfigurationFile);
launcherConfiguration =
LauncherConfiguration.Deserialize(await File.ReadAllTextAsync(options.LauncherConfigurationFile));
}
catch (Exception e)
{
if (!(options.MergeLegacyConfigIfExists && File.Exists(options.LegacyConfigurationFile)))
Log.Verbose("Reading launcher config file.");
try
{
if (File.Exists(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("Using command line parameters only.", options.LauncherConfigurationFile);
options.LauncherConfigurationFile = Path.GetFullPath(options.LauncherConfigurationFile);
launcherConfiguration = LauncherConfiguration.Deserialize(await File.ReadAllTextAsync(options.LauncherConfigurationFile));
}
}

Log.Verbose("Merging legacy launcher config file.");
if (options.MergeLegacyConfigIfExists && File.Exists(options.LegacyConfigurationFile))
{
var legacyConfig = await LegacyConfigFileReader.ReadLegacyConfigFile(options.LegacyConfigurationFile);
launcherConfiguration.OverwriteWith(legacyConfig);
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);
}
else
{
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))
{
var legacyConfig = await LegacyConfigFileReader.ReadLegacyConfigFile(options.LegacyConfigurationFile);
launcherConfiguration.OverwriteWith(legacyConfig);

var configFileDirectory = Path.GetDirectoryName(Path.GetFullPath(options.LauncherConfigurationFile));
if (configFileDirectory is not null) Directory.CreateDirectory(configFileDirectory);
var configFileDirectory = Path.GetDirectoryName(Path.GetFullPath(options.LauncherConfigurationFile));
if (configFileDirectory is not null)
{
Directory.CreateDirectory(configFileDirectory);
}

await File.WriteAllTextAsync(options.LauncherConfigurationFile, legacyConfig.Serialize());
await File.WriteAllTextAsync(options.LauncherConfigurationFile, legacyConfig.Serialize());

var fi = new FileInfo(options.LegacyConfigurationFile);
fi.CopyTo(options.LegacyConfigurationFile + ".legacy");
fi.Delete();
}
var fi = new FileInfo(options.LegacyConfigurationFile);
fi.CopyTo(options.LegacyConfigurationFile + ".legacy");
fi.Delete();
}

Log.Verbose("Merging launcher cli args.");
launcherConfiguration.OverwriteWith(options.ArgsLauncherConfiguration);
Expand Down Expand Up @@ -202,53 +199,54 @@ public static async Task<int> HandleAsync<O, S>(
Log.Fatal(e, "Could not read Cashbox configuration file.");
}

var cashboxConfiguration = new ftCashBoxConfiguration();
try
{
cashboxConfiguration =
CashBoxConfigurationExt.Deserialize(
await File.ReadAllTextAsync(launcherConfiguration.CashboxConfigurationFile!));
if (clientEcdh is not null) cashboxConfiguration.Decrypt(launcherConfiguration, clientEcdh);
}
catch (Exception e)
{
// will exit with non-zero exit code later.
Log.Fatal(e, "Could not parse Cashbox configuration.");
}
var cashboxConfiguration = new ftCashBoxConfiguration();
try
{
cashboxConfiguration = CashBoxConfigurationExt.Deserialize(await File.ReadAllTextAsync(launcherConfiguration.CashboxConfigurationFile!));
if (clientEcdh is not null) { cashboxConfiguration.Decrypt(launcherConfiguration, clientEcdh); }
}
catch (Exception e)
{
// will exit with non-zero exit code later.
Log.Fatal(e, "Could not parse Cashbox configuration.");
}

// Previous log messages will be logged here using this logger.
Log.Logger = new LoggerConfiguration()
.AddLoggingConfiguration(launcherConfiguration)
.AddFileLoggingConfiguration(launcherConfiguration,
new[] { "fiskaltrust.Launcher", launcherConfiguration.CashboxId?.ToString() })
.Enrich.FromLogContext()
.CreateLogger();
// Previous log messages will be logged here using this logger.
Log.Logger = new LoggerConfiguration()
.AddLoggingConfiguration(launcherConfiguration)
.AddFileLoggingConfiguration(launcherConfiguration, new[] { "fiskaltrust.Launcher", launcherConfiguration.CashboxId?.ToString() })
.Enrich.FromLogContext()
.CreateLogger();

foreach (var logEvent in collectionSink.Events) Log.Write(logEvent);
foreach (var logEvent in collectionSink.Events)
{
Log.Write(logEvent);
}

// If any critical errors occured, we exit with a non-zero exit code.
// In many cases we don't want to immediately exit the application,
// but we want to log the error and continue and see what else is going on before we exit.
if (collectionSink.Events.Where(e => e.Level == LogEventLevel.Fatal).Any()) return 1;
// If any critical errors occured, we exit with a non-zero exit code.
// In many cases we don't want to immediately exit the application,
// but we want to log the error and continue and see what else is going on before we exit.
if (collectionSink.Events.Where(e => e.Level == LogEventLevel.Fatal).Any())
{
return 1;
}

Log.Debug("Launcher Configuration File: {LauncherConfigurationFile}", options.LauncherConfigurationFile);
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));

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));
}
catch (Exception e)
{
Log.Warning(e, "Error decrypring launcher configuration file.");
}
try
{
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>());
}
Expand Down Expand Up @@ -297,13 +295,11 @@ private static async Task EnsureServiceDirectoryExists(LauncherConfiguration con
}
}

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 clientEcdhPath = Path.Combine(serviceFolder, $"client-{cashboxId}.ecdh");
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 clientEcdhPath = Path.Combine(serviceFolder, $"client-{cashboxId}.ecdh");

if (File.Exists(clientEcdhPath))
try
Expand Down

0 comments on commit 2c3d294

Please sign in to comment.