// 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.Reflection;
using System.Runtime.Versioning;
using System.Web;
using Duplicati.Library.Interface;
using Duplicati.Library.SecretProvider.LibSecret;
using Duplicati.Library.Utility;
namespace Duplicati.Library.SecretProvider;
///
/// Secret provider that reads secrets from libsecret on Linux
///
[SupportedOSPlatform("linux")]
public class LibSecretLinuxProvider : ISecretProvider
{
///
public string Key => "libsecret";
///
public string DisplayName => Strings.LibSecretLinuxProvider.DisplayName;
///
public string Description => Strings.LibSecretLinuxProvider.Description;
///
/// Cached support check for libsecret so we only evaluate availability once.
///
private static readonly Lazy> _isSupported = new(static () =>
{
if (!OperatingSystem.IsLinux())
return Task.FromResult(false);
return SecretCollection.IsSupported(CancellationToken.None);
});
///
public Task IsSupported(CancellationToken cancellationToken) => _isSupported.Value;
///
public bool IsSetSupported => true;
///
/// The configuration for the secret provider
///
private class LibSecretConfig : ICommandLineArgumentMapper
{
///
/// The collection to use
///
public string Collection { get; set; } = "default";
///
/// Whether the collection name is case sensitive
///
public bool CaseSensitive { get; set; }
///
/// Whether the collection should automatically be created when storing secrets if it does not exist.
///
public bool NoAutoCreateCollection { get; set; }
///
/// Gets the command line argument description for the given name
///
/// The name of the argument
/// The description or null if not found
public static CommandLineArgumentDescriptionAttribute? GetCommandLineArgumentDescription(string name)
=> name switch
{
nameof(Collection) => new CommandLineArgumentDescriptionAttribute() { Name = "collection", Type = CommandLineArgument.ArgumentType.String, ShortDescription = Strings.LibSecretLinuxProvider.CollectionDescriptionShort, LongDescription = Strings.LibSecretLinuxProvider.CollectionDescriptionLong },
nameof(CaseSensitive) => new CommandLineArgumentDescriptionAttribute() { Name = "case-sensitive", Type = CommandLineArgument.ArgumentType.Boolean, ShortDescription = Strings.LibSecretLinuxProvider.CaseSensitiveDescriptionShort, LongDescription = Strings.LibSecretLinuxProvider.CaseSensitiveDescriptionLong },
nameof(NoAutoCreateCollection) => new CommandLineArgumentDescriptionAttribute() { Name = "no-autocreate-collection", Type = CommandLineArgument.ArgumentType.Boolean, ShortDescription = Strings.LibSecretLinuxProvider.NoAutoCreateCollectionDescriptionShort, LongDescription = Strings.LibSecretLinuxProvider.NoAutoCreateCollectionDescriptionLong },
_ => null,
};
///
CommandLineArgumentDescriptionAttribute? ICommandLineArgumentMapper.GetCommandLineArgumentDescription(MemberInfo mi)
=> GetCommandLineArgumentDescription(mi.Name);
}
///
/// The configuration for the secret provider; null if not initialized
///
private LibSecretConfig? _cfg;
///
/// The secret collection
///
private SecretCollection? _collection;
///
public IList SupportedCommands
=> CommandLineArgumentMapper.MapArguments(new LibSecretConfig())
.ToList();
///
public async Task InitializeAsync(System.Uri config, CancellationToken cancellationToken)
{
if (!OperatingSystem.IsLinux())
throw new PlatformNotSupportedException("LibSecret is only supported on Linux");
var args = HttpUtility.ParseQueryString(config.Query);
_cfg = CommandLineArgumentMapper.ApplyArguments(new LibSecretConfig(), args);
if (string.IsNullOrWhiteSpace(_cfg.Collection))
throw new UserInformationException("The collection must be specified", "CollectionRequired");
_collection = await SecretCollection.CreateAsync(_cfg.Collection, !_cfg.NoAutoCreateCollection, cancellationToken).ConfigureAwait(false);
await _collection.UnlockAsync().ConfigureAwait(false);
}
///
public Task> ResolveSecretsAsync(IEnumerable keys, CancellationToken cancellationToken)
{
if (_cfg is null || _collection is null)
throw new InvalidOperationException("The secret provider has not been initialized");
if (!OperatingSystem.IsLinux())
throw new PlatformNotSupportedException("LibSecret is only supported on Linux");
return _collection.GetSecretsAsync(keys, _cfg.CaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase);
}
///
public async Task SetSecretAsync(string key, string value, bool overwrite, CancellationToken cancellationToken)
{
if (_cfg is null || _collection is null)
throw new InvalidOperationException("The secret provider has not been initialized");
if (!OperatingSystem.IsLinux())
throw new PlatformNotSupportedException("LibSecret is only supported on Linux");
var comparer = _cfg.CaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;
await _collection.StoreSecretAsync(key, value, overwrite, comparer, cancellationToken).ConfigureAwait(false);
}
///
/// Checks whether the specified collection exists
///
/// The cancellation token.
/// >True if the collection exists; otherwise false
public async Task DoesCollectionExist(CancellationToken cancellationToken)
{
if (_cfg is null)
throw new InvalidOperationException("The secret provider has not been initialized");
if (!OperatingSystem.IsLinux())
throw new PlatformNotSupportedException("LibSecret is only supported on Linux");
var actual = await SecretCollection.CollectionExists(_cfg.Collection, cancellationToken);
if (actual || !_cfg.Collection.Equals("default", StringComparison.OrdinalIgnoreCase))
return actual;
return await SecretCollection.CollectionExists(SecretCollection.DefaultCollectionActualName, cancellationToken);
}
}