diff --git a/Duplicati/Library/Backend/GoogleServices/Duplicati.Library.Backend.GoogleServices.csproj b/Duplicati/Library/Backend/GoogleServices/Duplicati.Library.Backend.GoogleServices.csproj index 7cef28639..cfee00a08 100644 --- a/Duplicati/Library/Backend/GoogleServices/Duplicati.Library.Backend.GoogleServices.csproj +++ b/Duplicati/Library/Backend/GoogleServices/Duplicati.Library.Backend.GoogleServices.csproj @@ -17,6 +17,7 @@ + diff --git a/Duplicati/Library/Backend/GoogleServices/GoogleCloudStorage.cs b/Duplicati/Library/Backend/GoogleServices/GoogleCloudStorage.cs index 27667e9c8..c26073e6a 100644 --- a/Duplicati/Library/Backend/GoogleServices/GoogleCloudStorage.cs +++ b/Duplicati/Library/Backend/GoogleServices/GoogleCloudStorage.cs @@ -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(), ]; diff --git a/Duplicati/Library/Backend/GoogleServices/GoogleCommon.cs b/Duplicati/Library/Backend/GoogleServices/GoogleCommon.cs index a512dd105..e96cfd38f 100644 --- a/Duplicati/Library/Backend/GoogleServices/GoogleCommon.cs +++ b/Duplicati/Library/Backend/GoogleServices/GoogleCommon.cs @@ -45,7 +45,7 @@ namespace Duplicati.Library.Backend.GoogleServices /// The read write timeout. /// The cancellation token. /// Tuple with the range and the response. - private static async Task<(long, T? Response)> QueryUploadRange(OAuthHelperHttpClient oauth, string uploaduri, long streamlength, TimeSpan shortTimeout, TimeSpan readWriteTimeout, CancellationToken cancellationToken) + private static async Task<(long, T? Response)> QueryUploadRange(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 /// The HTTP Method. /// The type of data to upload as metadata. /// The type of data returned from the upload. - public static async Task ChunkedUploadWithResumeAsync(OAuthHelperHttpClient oauth, TRequest requestdata, string url, Stream stream, TimeSpan shortTimeout, TimeSpan readWriteTimeout, CancellationToken cancelToken, HttpMethod method) + public static async Task ChunkedUploadWithResumeAsync(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 /// The short request timeout. /// The read write timeout. /// The type of data in the response. - private static async Task ChunkedUploadAsync(OAuthHelperHttpClient oauth, string uploaduri, Stream stream, TimeSpan shortTimeout, TimeSpan readWriteTimeout, CancellationToken cancelToken) + private static async Task ChunkedUploadAsync(JsonWebHelperHttpClient oauth, string uploaduri, Stream stream, TimeSpan shortTimeout, TimeSpan readWriteTimeout, CancellationToken cancelToken) where T : class { var queryRange = false; diff --git a/Duplicati/Library/Backend/GoogleServices/ServiceAccountHttpClient.cs b/Duplicati/Library/Backend/GoogleServices/ServiceAccountHttpClient.cs new file mode 100644 index 000000000..22c20ec87 --- /dev/null +++ b/Duplicati/Library/Backend/GoogleServices/ServiceAccountHttpClient.cs @@ -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 +{ + /// + /// Minimal HTTP client that adds a service account access token to outgoing requests. + /// + 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 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; + } + } +} + diff --git a/Duplicati/Library/Backend/GoogleServices/Strings.cs b/Duplicati/Library/Backend/GoogleServices/Strings.cs index ebde26e13..0a504b306 100644 --- a/Duplicati/Library/Backend/GoogleServices/Strings.cs +++ b/Duplicati/Library/Backend/GoogleServices/Strings.cs @@ -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