// Copyright (C) 2025, The Duplicati Team
// https://duplicati.com, hello@duplicati.com
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System.Text.Json;
using Duplicati.Library.AutoUpdater;
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 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 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
);
///
/// Gets the default data folder for the settings file
///
/// The filename to use
/// The default storage folder
private static string GetDefaultStorageFolder(string filename)
// Ideally, this should use DataFolderManager.DATAFOLDER, but we cannot due to backwards compatibility
=> DataFolderLocator.GetDefaultStorageFolder(filename, true);
///
/// Loads the settings from the settings file
///
/// The password to use
/// The host URL 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 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(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,
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, DataFolderManager.DATAFOLDER))
.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 [];
}
}