Merge pull request #6516 from duplicati/feature/support-gcs-iam

Google IAM support
This commit is contained in:
Kenneth Skovhede
2025-09-23 09:04:43 +02:00
committed by GitHub
5 changed files with 93 additions and 8 deletions
@@ -17,6 +17,7 @@
<ProjectReference Include="..\..\Localization\Duplicati.Library.Localization.csproj" />
<ProjectReference Include="..\..\Utility\Duplicati.Library.Utility.csproj" />
<ProjectReference Include="..\..\Backend\OAuthHelper\Duplicati.Library.OAuthHelper.csproj" />
<PackageReference Include="Google.Apis.Auth" Version="1.67.0" />
</ItemGroup>
</Project>
@@ -24,6 +24,7 @@ using Duplicati.Library.Common.IO;
using Duplicati.Library.Interface;
using Duplicati.Library.Utility;
using Duplicati.Library.Utility.Options;
using Google.Apis.Auth.OAuth2;
using System.Net;
using System.Net.Http.Json;
using System.Runtime.CompilerServices;
@@ -40,11 +41,15 @@ namespace Duplicati.Library.Backend.GoogleCloudStorage
private const string LOCATION_OPTION = "gcs-location";
private const string STORAGECLASS_OPTION = "gcs-storage-class";
private const string SERVICE_ACCOUNT_JSON_OPTION = "gcs-service-account-json";
private const string SERVICE_ACCOUNT_FILE_OPTION = "gcs-service-account-file";
private const string CREDENTIAL_SCOPE = "https://www.googleapis.com/auth/devstorage.read_write";
private readonly string m_bucket;
private readonly string m_prefix;
private readonly string? m_project;
private readonly OAuthHelperHttpClient m_oauth;
private readonly JsonWebHelperHttpClient m_oauth;
private readonly string? m_location;
private readonly string? m_storage_class;
@@ -69,16 +74,32 @@ namespace Duplicati.Library.Backend.GoogleCloudStorage
if (m_prefix.StartsWith("/", StringComparison.Ordinal))
m_prefix = m_prefix.Substring(1);
var authId = AuthIdOptionsHelper.Parse(options)
.RequireCredentials(TOKEN_URL);
var serviceAccountFile = options.GetValueOrDefault(SERVICE_ACCOUNT_FILE_OPTION);
var serviceAccountJson = options.GetValueOrDefault(SERVICE_ACCOUNT_JSON_OPTION);
m_timeouts = TimeoutOptionsHelper.Parse(options);
m_project = options.GetValueOrDefault(PROJECT_OPTION);
m_location = options.GetValueOrDefault(LOCATION_OPTION);
m_storage_class = options.GetValueOrDefault(STORAGECLASS_OPTION);
m_oauth = new OAuthHelperHttpClient(authId.AuthId!, this.ProtocolKey, authId.OAuthUrl);
m_oauth.AutoAuthHeader = true;
if (!string.IsNullOrWhiteSpace(serviceAccountJson))
{
m_oauth = new ServiceAccountHttpClient(GoogleCredential.FromJson(serviceAccountJson).CreateScoped(CREDENTIAL_SCOPE));
}
else if (!string.IsNullOrWhiteSpace(serviceAccountFile))
{
m_oauth = new ServiceAccountHttpClient(GoogleCredential.FromFile(serviceAccountFile).CreateScoped(CREDENTIAL_SCOPE));
}
else
{
var authId = AuthIdOptionsHelper.Parse(options)
.RequireCredentials(TOKEN_URL);
var oauth = new OAuthHelperHttpClient(authId.AuthId!, this.ProtocolKey, authId.OAuthUrl)
{
AutoAuthHeader = true
};
m_oauth = oauth;
}
}
@@ -222,6 +243,8 @@ namespace Duplicati.Library.Backend.GoogleCloudStorage
new CommandLineArgument(LOCATION_OPTION, CommandLineArgument.ArgumentType.String, Strings.GoogleCloudStorage.LocationDescriptionShort, Strings.GoogleCloudStorage.LocationDescriptionLong(locations.ToString())),
new CommandLineArgument(STORAGECLASS_OPTION, CommandLineArgument.ArgumentType.String, Strings.GoogleCloudStorage.StorageclassDescriptionShort, Strings.GoogleCloudStorage.StorageclassDescriptionLong(storageClasses.ToString())),
.. AuthIdOptionsHelper.GetOptions(TOKEN_URL),
new CommandLineArgument(SERVICE_ACCOUNT_JSON_OPTION, CommandLineArgument.ArgumentType.String, Strings.GoogleCloudStorage.ServiceAccountJsonDescriptionShort, Strings.GoogleCloudStorage.ServiceAccountJsonDescriptionLong),
new CommandLineArgument(SERVICE_ACCOUNT_FILE_OPTION, CommandLineArgument.ArgumentType.String, Strings.GoogleCloudStorage.ServiceAccountFileDescriptionShort, Strings.GoogleCloudStorage.ServiceAccountFileDescriptionLong),
new CommandLineArgument(PROJECT_OPTION, CommandLineArgument.ArgumentType.String, Strings.GoogleCloudStorage.ProjectDescriptionShort, Strings.GoogleCloudStorage.ProjectDescriptionLong),
.. TimeoutOptionsHelper.GetOptions(),
];
@@ -45,7 +45,7 @@ namespace Duplicati.Library.Backend.GoogleServices
/// <param name="readWriteTimeout">The read write timeout.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Tuple with the range and the response.</returns>
private static async Task<(long, T? Response)> QueryUploadRange<T>(OAuthHelperHttpClient oauth, string uploaduri, long streamlength, TimeSpan shortTimeout, TimeSpan readWriteTimeout, CancellationToken cancellationToken)
private static async Task<(long, T? Response)> QueryUploadRange<T>(JsonWebHelperHttpClient oauth, string uploaduri, long streamlength, TimeSpan shortTimeout, TimeSpan readWriteTimeout, CancellationToken cancellationToken)
where T : class
{
using var req = await oauth.CreateRequestAsync(uploaduri, HttpMethod.Put, cancellationToken);
@@ -100,7 +100,7 @@ namespace Duplicati.Library.Backend.GoogleServices
/// <param name="method">The HTTP Method.</param>
/// <typeparam name="TRequest">The type of data to upload as metadata.</typeparam>
/// <typeparam name="TResponse">The type of data returned from the upload.</typeparam>
public static async Task<TResponse> ChunkedUploadWithResumeAsync<TRequest, TResponse>(OAuthHelperHttpClient oauth, TRequest requestdata, string url, Stream stream, TimeSpan shortTimeout, TimeSpan readWriteTimeout, CancellationToken cancelToken, HttpMethod method)
public static async Task<TResponse> ChunkedUploadWithResumeAsync<TRequest, TResponse>(JsonWebHelperHttpClient oauth, TRequest requestdata, string url, Stream stream, TimeSpan shortTimeout, TimeSpan readWriteTimeout, CancellationToken cancelToken, HttpMethod method)
where TRequest : class
where TResponse : class
{
@@ -135,7 +135,7 @@ namespace Duplicati.Library.Backend.GoogleServices
/// <param name="shortTimeout">The short request timeout.</param>
/// <param name="readWriteTimeout">The read write timeout.</param>
/// <typeparam name="T">The type of data in the response.</typeparam>
private static async Task<T> ChunkedUploadAsync<T>(OAuthHelperHttpClient oauth, string uploaduri, Stream stream, TimeSpan shortTimeout, TimeSpan readWriteTimeout, CancellationToken cancelToken)
private static async Task<T> ChunkedUploadAsync<T>(JsonWebHelperHttpClient oauth, string uploaduri, Stream stream, TimeSpan shortTimeout, TimeSpan readWriteTimeout, CancellationToken cancelToken)
where T : class
{
var queryRange = false;
@@ -0,0 +1,57 @@
// 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.Net.Http.Headers;
using Duplicati.Library.Utility;
using Google.Apis.Auth.OAuth2;
namespace Duplicati.Library.Backend.GoogleServices
{
/// <summary>
/// Minimal HTTP client that adds a service account access token to outgoing requests.
/// </summary>
internal class ServiceAccountHttpClient : JsonWebHelperHttpClient
{
private readonly ITokenAccess _credential;
private static HttpClient CreateHttpClientWithInfiniteTimeout()
{
var client = HttpClientHelper.CreateClient();
client.Timeout = Timeout.InfiniteTimeSpan;
return client;
}
public ServiceAccountHttpClient(GoogleCredential credential)
: base(CreateHttpClientWithInfiniteTimeout())
{
_credential = (ITokenAccess)credential;
}
public override async Task<HttpRequestMessage> CreateRequestAsync(string url, HttpMethod method, CancellationToken cancellationToken)
{
var req = await base.CreateRequestAsync(url, method, cancellationToken).ConfigureAwait(false);
var token = await _credential.GetAccessTokenForRequestAsync(null, cancellationToken).ConfigureAwait(false);
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
return req;
}
}
}
@@ -36,6 +36,10 @@ namespace Duplicati.Library.Backend.Strings
public static string StorageclassDescriptionShort { get { return LC.L(@"Specify storage class for creating a bucket"); } }
public static string ProjectDescriptionLong { get { return LC.L(@"This option is only used when creating new buckets. Use this option to supply the project ID that the bucket is attached to. The project determines where usage charges are applied."); } }
public static string ProjectDescriptionShort { get { return LC.L(@"Specify project for creating a bucket"); } }
public static string ServiceAccountJsonDescriptionShort { get { return LC.L(@"Service account JSON"); } }
public static string ServiceAccountJsonDescriptionLong { get { return LC.L(@"String with JSON credentials for a Google Cloud service account. When set, AuthID is not required."); } }
public static string ServiceAccountFileDescriptionShort { get { return LC.L(@"Service account JSON"); } }
public static string ServiceAccountFileDescriptionLong { get { return LC.L(@"Path to a file with JSON credentials for a Google Cloud service account. When set, AuthID is not required."); } }
}
internal static class GoogleDrive