-
Notifications
You must be signed in to change notification settings - Fork 524
/
ImpersonatedCredential.cs
325 lines (284 loc) · 16 KB
/
ImpersonatedCredential.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/*
Copyright 2021 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using Google.Apis.Auth.OAuth2.Requests;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Http;
using Google.Apis.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Apis.Auth.OAuth2
{
/// <summary>
/// Allows a service account or user credential to impersonate a service account.
/// See https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials
/// and https://cloud.google.com/iam/docs/impersonating-service-accounts
/// for more information.
/// </summary>
public sealed class ImpersonatedCredential : ServiceCredential, IOidcTokenProvider, IGoogleCredential, IBlobSigner
{
/// <summary>An initializer class for the impersonated credential. </summary>
new public sealed class Initializer : ServiceCredential.Initializer
{
private static readonly TimeSpan DefaultLifetime = TimeSpan.FromHours(1);
/// <summary>
/// Gets the service account to impersonate.
/// </summary>
public string TargetPrincipal { get; }
/// <summary>
/// Gets the chained list of delegate service accounts. May be null or empty.
/// </summary>
public IEnumerable<string> DelegateAccounts { get; set; }
/// <summary>
/// Gets or sets for how long the delegated credential should be valid.
/// Defaults to 1 hour or 3600 seconds.
/// </summary>
public TimeSpan Lifetime { get; set; } = DefaultLifetime;
/// <summary>
/// Indicates whether the credential has a custom access token URL instead of
/// the one built by using <see cref="GoogleAuthConsts.IamAccessTokenEndpointFormatString"/>
/// and the target principal.
/// </summary>
/// <remarks>
/// <para>This is useful for bundled or implicit impersonation scenarios in which the access token
/// URL may be specified on its own as part of the credential configuration. In those cases,
/// some <see cref="ImpersonatedCredential"/> operations are not supported, for instance operations from
/// <see cref="IBlobSigner"/> or <see cref="IOidcTokenProvider"/>.</para>
/// <para>Note that we keep this property internal as no <see cref="ImpersonatedCredential"/>
/// instance will be exposed that has been built with a custom token URL.</para>
/// </remarks>
internal bool HasCustomTokenUrl { get; }
/// <summary>Constructs a new initializer.</summary>
/// <param name="targetPrincipal">The principal that will be impersonated. Must not be null, as it will be used
/// to build the URL to obtaing the impersonated access token from.</param>
public Initializer(string targetPrincipal)
: base(GetDefaultTokenUrl(targetPrincipal.ThrowIfNull(nameof(targetPrincipal)))) =>
TargetPrincipal = targetPrincipal;
/// <summary>
/// Constructus a new initializer.
/// </summary>
/// <param name="customTokenUrl">The URL to obtain the impersonated access token from.</param>
/// <param name="maybeTargetPrincipal">The target principal, if known, that will be impersonated. May be null.</param>
/// <remarks>Because the <paramref name="customTokenUrl"/> is all that is needed for obtaining the impersonated
/// access token, <paramref name="maybeTargetPrincipal"/> is just informational when the
/// <see cref="Initializer(string, string)"/> constructor overload is used.</remarks>
internal Initializer(string customTokenUrl, string maybeTargetPrincipal)
: base(customTokenUrl.ThrowIfNullOrEmpty(nameof(customTokenUrl)))
{
TargetPrincipal = maybeTargetPrincipal;
HasCustomTokenUrl = maybeTargetPrincipal is null
|| GetDefaultTokenUrl(maybeTargetPrincipal) != customTokenUrl;
}
internal Initializer(ImpersonatedCredential other) : base(other)
{
TargetPrincipal = other.TargetPrincipal;
DelegateAccounts = other.DelegateAccounts;
Lifetime = other.Lifetime;
HasCustomTokenUrl = other.HasCustomTokenUrl;
}
internal Initializer(Initializer other) : base (other)
{
TargetPrincipal = other.TargetPrincipal;
DelegateAccounts = other.DelegateAccounts?.ToList().AsReadOnly() ?? Enumerable.Empty<string>();
Lifetime = other.Lifetime;
HasCustomTokenUrl = other.HasCustomTokenUrl;
}
private static string GetDefaultTokenUrl(string targetPrincipal) =>
string.Format(GoogleAuthConsts.IamAccessTokenEndpointFormatString, targetPrincipal);
}
/// <summary>
/// Gets the source credential used to acquire the impersonated credentials.
/// </summary>
public GoogleCredential SourceCredential => HttpClientInitializers.OfType<GoogleCredential>().Single();
/// <summary>
/// Gets the service account to impersonate.
/// </summary>
public string TargetPrincipal { get; }
/// <summary>
/// Gets the chained list of delegate service accounts. May be empty.
/// </summary>
public IEnumerable<string> DelegateAccounts { get; }
/// <summary>
/// Gets the lifetime of the delegated credential.
/// This is how long the delegated credential should be valid from the time
/// of the first request made with this credential.
/// </summary>
public TimeSpan Lifetime { get; }
/// <inheritdoc/>
bool IGoogleCredential.HasExplicitScopes => Scopes?.Any() == true;
/// <inheritdoc/>
bool IGoogleCredential.SupportsExplicitScopes => true;
/// <summary>
/// Indicates whether the credential has a custom access token URL instead of
/// the one built by using <see cref="GoogleAuthConsts.IamAccessTokenEndpointFormatString"/>
/// and the target principal.
/// </summary>
/// <remarks>
/// <para>This is useful for bundled or implicit impersonation scenarios in which the access token
/// URL may be specified on its own as part of the credential configuration. In those cases,
/// some <see cref="ImpersonatedCredential"/> operations are not supported, for instance operations from
/// <see cref="IBlobSigner"/> or <see cref="IOidcTokenProvider"/>.</para>
/// <para>Note that we keep this property internal as no <see cref="ImpersonatedCredential"/>
/// instance will be exposed that has been built with a custom token URL. We only build <see cref="ImpersonatedCredential"/>s
/// with custom token URLs when <see cref="ExternalAccountCredential"/>s are configured with bundled or implicit impersonation,
/// where <see cref="ExternalAccountCredential.ImplicitlyImpersonated"/> is only internal.
/// </para>
/// </remarks>
internal bool HasCustomTokenUrl { get; }
internal static ImpersonatedCredential Create(GoogleCredential sourceCredential, Initializer initializer)
{
initializer.ThrowIfNull(nameof(initializer));
sourceCredential.ThrowIfNull(nameof(sourceCredential));
if (initializer.Lifetime < TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(initializer.Lifetime), $"Must be greater or equal to {nameof(TimeSpan.Zero)}");
}
if (!(sourceCredential.UnderlyingCredential is ServiceAccountCredential
|| sourceCredential.UnderlyingCredential is UserCredential
|| sourceCredential.UnderlyingCredential is ExternalAccountCredential
|| sourceCredential.UnderlyingCredential is ComputeCredential))
{
throw new InvalidOperationException(
$"Only {nameof(ServiceAccountCredential)}," +
$"{nameof(UserCredential)}, " +
$"{nameof(ExternalAccountCredential)} " +
$"and {nameof(ComputeCredential)} support impersonation.");
}
if (sourceCredential.UnderlyingCredential is ExternalAccountCredential externalCred && externalCred.ServiceAccountImpersonationUrl is string)
{
throw new InvalidOperationException($"Only {nameof(ExternalAccountCredential)}s that have no impersonation configured via service_account_impersonation_url support explicit impersonation.");
}
// We ourselves modify the client supplied initializer, so let's make a copy first.
initializer = new Initializer(initializer);
initializer.HttpClientInitializers.Add(sourceCredential.CreateScoped(new string[] { GoogleAuthConsts.IamScope }));
return new ImpersonatedCredential(initializer);
}
/// <summary>Constructs a new impersonated credential using the given initializer.</summary>
private ImpersonatedCredential(Initializer initializer) : base(initializer)
{
TargetPrincipal = initializer.TargetPrincipal;
// We just copied tha initializer on the Create method so we know this
// to be our own local copy. We can avoid copying these collections here.
DelegateAccounts = initializer.DelegateAccounts;
Lifetime = initializer.Lifetime;
HasCustomTokenUrl = initializer.HasCustomTokenUrl;
}
/// <inheritdoc/>
IGoogleCredential IGoogleCredential.WithQuotaProject(string quotaProject) =>
new ImpersonatedCredential(new Initializer(this) { QuotaProject = quotaProject });
/// <inheritdoc/>
IGoogleCredential IGoogleCredential.MaybeWithScopes(IEnumerable<string> scopes) =>
new ImpersonatedCredential(new Initializer(this) { Scopes = scopes });
/// <inheritdoc/>
IGoogleCredential IGoogleCredential.WithUserForDomainWideDelegation(string user) =>
throw new InvalidOperationException($"{nameof(ImpersonatedCredential)} does not support Domain-Wide Delegation");
/// <inheritdoc/>
IGoogleCredential IGoogleCredential.WithHttpClientFactory(IHttpClientFactory httpClientFactory) =>
new ImpersonatedCredential(new Initializer(this) { HttpClientFactory = httpClientFactory });
/// <inheritdoc/>
public override async Task<bool> RequestAccessTokenAsync(CancellationToken taskCancellationToken)
{
var request = new ImpersonationAccessTokenRequest
{
DelegateAccounts = DelegateAccounts,
Scopes = Scopes,
Lifetime = $"{(int)Lifetime.TotalSeconds}s"
};
Token = await request.PostJsonAsync(HttpClient, TokenServerUrl, Clock, Logger, taskCancellationToken)
.ConfigureAwait(false);
return true;
}
/// <inheritdoc/>
public Task<OidcToken> GetOidcTokenAsync(OidcTokenOptions options, CancellationToken cancellationToken = default)
{
ThrowIfCustomTokenUrl();
options.ThrowIfNull(nameof(options));
// If at some point some properties are added to OidcToken that depend on the token having been fetched
// then initialize the token here.
TokenRefreshManager tokenRefreshManager = null;
tokenRefreshManager = new TokenRefreshManager(ct => RefreshOidcTokenAsync(tokenRefreshManager, options, ct), Clock, Logger);
return Task.FromResult(new OidcToken(tokenRefreshManager));
}
private async Task<bool> RefreshOidcTokenAsync(TokenRefreshManager caller, OidcTokenOptions oidcTokenOptions, CancellationToken cancellationToken)
{
ThrowIfCustomTokenUrl();
var request = new ImpersonationOIdCTokenRequest
{
DelegateAccounts = DelegateAccounts,
Audience = oidcTokenOptions.TargetAudience,
IncludeEmail = true
};
var oidcTokenUrl = string.Format(GoogleAuthConsts.IamIdTokenEndpointFormatString, TargetPrincipal);
caller.Token = await request.PostJsonAsync(HttpClient, oidcTokenUrl, Clock, Logger, cancellationToken)
.ConfigureAwait(false);
return true;
}
/// <summary>
/// Signs the provided blob using the private key associated with the impersonated service account.
/// </summary>
/// <param name="blob">The blob to sign.</param>
/// <param name="cancellationToken">Cancellation token to cancel operation.</param>
/// <returns>The base64 encoded signature.</returns>
/// <exception cref="HttpRequestException">When signing request fails.</exception>
/// <exception cref="JsonException">When signing response is not a valid JSON.</exception>
public async Task<string> SignBlobAsync(byte[] blob, CancellationToken cancellationToken = default)
{
ThrowIfCustomTokenUrl();
var request = new IamSignBlobRequest
{
DelegateAccounts = DelegateAccounts,
Payload = blob
};
var signBlobUrl = string.Format(GoogleAuthConsts.IamSignEndpointFormatString, TargetPrincipal);
var response = await request.PostJsonAsync<IamSignBlobResponse>(HttpClient, signBlobUrl, cancellationToken)
.ConfigureAwait(false);
return response.SignedBlob;
}
private void ThrowIfCustomTokenUrl()
{
if (HasCustomTokenUrl)
{
// If the impersonated credential has a custom access token URL we don't know how the OIDC URL and blob signing
// URL may look like, so we cannot support those operations.
// For supporting TPC, regional endpoints, etc. we only need to change the definition of custom, which at the moment is:
// everything different of GoogleAuthConsts.IamAccessTokenEndpointFormatString.
throw new InvalidOperationException("Operation not supported when a custom access token URL has been specified.");
}
}
/// <summary>
/// Attempts to extract the target principal ID from the impersonation URL which is possible if the URL looks like
/// https://host/segment-1/.../segment-n/target-principal-ID:generateAccessToken.
/// It's OK if we can't though as for fetching the impersonated access token we have the impersonation URL as a whole.
/// It's just a nice to have, as the user may be able to execute extra operations with the impersonated credential, like
/// signing a blob of fetching its OIDC token.
/// </summary>
internal static string ExtractTargetPrincipal(string url)
{
int start = url.LastIndexOf('/') + 1;
if (start == 0 || start >= url.Length)
{
return null;
}
int afterEnd = url.IndexOf($":{GoogleAuthConsts.IamAccessTokenVerb}", StringComparison.Ordinal);
if (afterEnd == -1 || afterEnd <= start)
{
return null;
}
return url.Substring(start, afterEnd - start);
}
}
}