using System.Text.Json;
using Duplicati.Library.DynamicLoader;
using Duplicati.Library.Encryption;
using Duplicati.Library.Interface;
using Duplicati.Library.Main;
using Duplicati.Library.Utility;
namespace Duplicati.CommandLine.ServerUtil;
///
/// Settings instance for the server utility.
///
/// The commandline password
/// The saved refresh token
/// The host url to connect to
/// The server datafolder for password-free connections
/// The settings file where data is loaded/saved
/// Whether to disable TLS/SSL certificate trust check
/// The encryption key to use for the settings file
/// The secret provider to use for reading secrets
/// The pattern to use for the secret provider
/// The SHA1 hash of the host certificate to accept
public sealed record Settings(
string? Password,
string? RefreshToken,
System.Uri HostUrl,
string? ServerDatafolder,
string SettingsFile,
bool Insecure,
EncryptedFieldHelper.KeyInstance? Key,
ISecretProvider? SecretProvider,
string SecretProviderPattern,
string? AcceptedHostCertificate
)
{
///
/// The JSON serialized settings for a single host
///
/// Encrypted refresh token
/// The host url to connect to
/// The server datafolder, if any
private sealed record PersistedSettings(
string? RefreshToken,
System.Uri HostUrl,
string? ServerDatafolder
);
private static string GetDefaultStorageFolder(string filename)
{
var folder = DatabaseLocator.GetDefaultStorageFolderWithDebugSupport(filename);
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
return folder;
}
///
/// Loads the settings from the settings file
///
/// The password to use
/// The host URL to use
/// The server data folder to use
/// The settings file to use
/// Whether to disable TLS/SSL certificate trust check
/// The encryption key to use
/// The secret provider to use
/// The secret provider cache level to use
/// The secret provider pattern to use
/// The SHA1 hash of the host certificate to accept
/// The loaded settings
public static Settings Load(string? password, System.Uri? hostUrl, string? serverDataFolder, string settingsFile, bool insecure, string? settingsPassphrase, string? secretProvider, SecretProviderHelper.CachingLevel secretProviderCache, string secretProviderPattern, string? acceptedHostCertificate)
{
hostUrl ??= new System.Uri("http://localhost:8200");
ISecretProvider? secretInstance = null;
if (!string.IsNullOrWhiteSpace(secretProvider))
{
var secretProviderInstance = SecretProviderLoader.CreateInstance(secretProvider);
// Map into expected structure
var opts = new Dictionary
{
{ "secret-provider", secretProvider },
{ "secret-provider-pattern", secretProviderPattern },
{ "secret-provider-cache", secretProviderCache.ToString() },
{ "password", password },
{ "settings-encryption-key", settingsPassphrase }
};
var args = new[] { hostUrl };
secretInstance = SecretProviderHelper.ApplySecretProviderAsync(args, [], opts, Library.Utility.TempFolder.SystemTempPath, null, CancellationToken.None).Await();
// Read back transformed values
hostUrl = args[0];
password = opts["password"];
settingsPassphrase = opts["settings-encryption-key"];
}
if (string.IsNullOrWhiteSpace(serverDataFolder))
serverDataFolder = GetDefaultStorageFolder("Duplicati-server.sqlite");
if (!string.IsNullOrWhiteSpace(settingsFile) && !Path.IsPathRooted(settingsFile))
settingsFile = Path.Combine(GetDefaultStorageFolder(settingsFile), settingsFile);
var key = EncryptedFieldHelper.KeyInstance.CreateKeyIfValid(settingsPassphrase);
var persistedSettings = LoadSettings(settingsFile, key)
.FirstOrDefault(x => x.HostUrl == hostUrl);
return new Settings(
password,
persistedSettings?.RefreshToken,
hostUrl,
serverDataFolder,
settingsFile,
insecure,
key,
secretInstance,
secretProviderPattern,
acceptedHostCertificate
);
}
///
/// Replaces secrets inside arguments and options
///
/// The arguments to replace
/// The options to replace
/// The task to await
public Task ReplaceSecrets(Dictionary options)
{
if (SecretProvider == null)
return Task.CompletedTask;
return SecretProviderHelper.ReplaceSecretsAsync(SecretProvider, [], [], options, SecretProviderPattern, CancellationToken.None);
}
///
/// Saves the settings to the settings file
///
public void Save()
{
var thisKey = Key;
if (!string.IsNullOrWhiteSpace(RefreshToken))
{
if (Key == null)
{
Console.WriteLine("Warning: The encryption key is missing, saving login token without encryption");
}
else if (Key?.IsBlacklisted ?? false)
{
Console.WriteLine("Warning: The current encryption key is blacklisted and cannot be used, saving login token without encryption");
thisKey = null;
}
}
File.WriteAllText(SettingsFile, JsonSerializer.Serialize(LoadSettings(SettingsFile, thisKey)
.Where(x => x.HostUrl != HostUrl)
.Append(new PersistedSettings(RefreshToken, HostUrl, ServerDatafolder))
.Select(x => x with
{
RefreshToken = string.IsNullOrWhiteSpace(x.RefreshToken) || thisKey == null
? x.RefreshToken
: EncryptedFieldHelper.Encrypt(x.RefreshToken, thisKey)
})
));
}
///
/// Gets a connection to the server
///
/// The connection
public Task GetConnection()
{
return Connection.Connect(this);
}
///
/// Loads the settings from the settings file
///
/// The filename to load
/// The encryption key to use
/// The loaded settings
private static List LoadSettings(string filename, EncryptedFieldHelper.KeyInstance? key)
{
if (File.Exists(filename))
return (JsonSerializer.Deserialize>(File.ReadAllText(filename)) ?? [])
.Select(x => x with { RefreshToken = EncryptedFieldHelper.Decrypt(x.RefreshToken, key) })
.ToList();
return [];
}
}