Repository navigation
Use Trusted Publishing for CloudTest E2E Test execution #141
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
14 changes: 14 additions & 0 deletions
14
src/NuGet.Services.EndToEnd/Support/Configuration/TrustedPublishingSettings.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| // Copyright (c) .NET Foundation. All rights reserved. | ||
| // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
|
||
| namespace NuGet.Services.EndToEnd.Support | ||
| { | ||
| public sealed class TrustedPublishingSettings | ||
| { | ||
| public string Environment { get; set; } | ||
|
|
||
| public string ResourceUri { get; set; } | ||
|
|
||
| public string[] AllowedGalleryHosts { get; set; } | ||
| } | ||
| } |
209 changes: 209 additions & 0 deletions
209
src/NuGet.Services.EndToEnd/Support/E2EPublishingKeyProvider.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,209 @@ | ||
| // Copyright (c) .NET Foundation. All rights reserved. | ||
| // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
|
||
| using System; | ||
| using System.Linq; | ||
| using System.Net.Http; | ||
| using System.Net.Http.Headers; | ||
| using System.Text; | ||
| using System.Text.RegularExpressions; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Azure.Core; | ||
| using Azure.Identity; | ||
| using Newtonsoft.Json; | ||
|
|
||
| namespace NuGet.Services.EndToEnd.Support | ||
| { | ||
| /// <summary> | ||
| /// Exchanges the CloudTest VM's managed identity token for a short-lived Gallery key. | ||
| /// This does not use the pipeline identity, developer credentials, or a stored API key. | ||
| /// </summary> | ||
| internal sealed class E2EPublishingKeyProvider | ||
| { | ||
| private readonly Func<string, TokenCredential> _createCredential; | ||
| private readonly Func<HttpClient> _createHttpClient; | ||
| private readonly Func<DateTimeOffset> _utcNow; | ||
|
|
||
| internal E2EPublishingKeyProvider() | ||
| : this(CreateCredential, CreateHttpClient, () => DateTimeOffset.UtcNow) | ||
| { | ||
| } | ||
|
|
||
| internal E2EPublishingKeyProvider( | ||
| Func<string, TokenCredential> createCredential, | ||
| Func<HttpClient> createHttpClient, | ||
| Func<DateTimeOffset> utcNow) | ||
| { | ||
| _createCredential = createCredential ?? throw new ArgumentNullException(nameof(createCredential)); | ||
| _createHttpClient = createHttpClient ?? throw new ArgumentNullException(nameof(createHttpClient)); | ||
| _utcNow = utcNow ?? throw new ArgumentNullException(nameof(utcNow)); | ||
| } | ||
|
|
||
| internal async Task<PublishingKey> AcquireAsync(TestSettings settings) | ||
| { | ||
| // Validate everything before constructing a credential or making any network request. | ||
| var context = GetContext(settings); | ||
| if (!Guid.TryParse(settings.ManagedIdentityClientId, out var clientId) || clientId == Guid.Empty) | ||
| { | ||
| throw new InvalidOperationException("E2E trusted publishing requires a non-empty managed identity client ID."); | ||
| } | ||
|
|
||
| AccessToken token; | ||
| try | ||
| { | ||
| var credential = _createCredential(clientId.ToString()); | ||
| var request = new TokenRequestContext(new[] { context.ResourceUri }); | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Azure.Identity 1.12.0 supports a bare resource URI for managed identity. Its IMDS implementation calls ScopesToResource(), which strips /.default when present and otherwise passes the resource through unchanged. |
||
| token = await credential.GetTokenAsync(request, CancellationToken.None).ConfigureAwait(false); | ||
| } | ||
| catch (Exception) | ||
| { | ||
| // SDK exceptions can contain HTTP details. | ||
| throw new InvalidOperationException("Cannot acquire an Entra token using the CloudTest managed identity."); | ||
| } | ||
|
|
||
| if (string.IsNullOrWhiteSpace(token.Token)) | ||
| { | ||
| throw new InvalidOperationException("Managed identity did not return an access token."); | ||
| } | ||
|
|
||
| using (var client = _createHttpClient()) | ||
| using (var request = new HttpRequestMessage(HttpMethod.Post, new Uri(context.GalleryUri, "api/v2/token"))) | ||
| { | ||
| request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.Token); | ||
| request.Headers.UserAgent.ParseAdd("NuGet-E2E-CloudTest/1.0"); | ||
| request.Content = new StringContent(JsonConvert.SerializeObject(new | ||
| { | ||
| username = settings.TestAccountOwner, | ||
| tokenType = "ApiKey" | ||
| }), Encoding.UTF8, "application/json"); | ||
|
|
||
| string content; | ||
| try | ||
| { | ||
| // Do not use SimpleHttpClient/RetryUtility here: a token can be exchanged only once. | ||
| using (var response = await client.SendAsync(request).ConfigureAwait(false)) | ||
| { | ||
| if (!response.IsSuccessStatusCode) | ||
| { | ||
| throw new InvalidOperationException( | ||
| $"Gallery token exchange failed (HTTP {(int)response.StatusCode}); not retrying. Check the environment policy and possible token replay."); | ||
| } | ||
|
|
||
| content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); | ||
| } | ||
| } | ||
| catch (HttpRequestException) | ||
| { | ||
| throw new InvalidOperationException("Gallery token exchange failed; not retrying an ambiguous request. Details omitted."); | ||
| } | ||
| catch (OperationCanceledException) | ||
| { | ||
| throw new InvalidOperationException("Gallery token exchange timed out or was canceled; not retrying an ambiguous request."); | ||
| } | ||
|
|
||
| PublishingKey result; | ||
| try | ||
| { | ||
| result = JsonConvert.DeserializeObject<PublishingKey>(content); | ||
| } | ||
| catch (JsonException) | ||
| { | ||
| throw new InvalidOperationException("Gallery returned invalid JSON; response omitted."); | ||
| } | ||
|
|
||
| if (result == null || result.TokenType != "ApiKey" || string.IsNullOrWhiteSpace(result.ApiKey)) | ||
| { | ||
| throw new InvalidOperationException("Gallery returned an invalid token exchange response. Expected tokenType 'ApiKey' and a non-empty apiKey."); | ||
| } | ||
|
|
||
| if (!result.Expires.HasValue || result.Expires.Value <= _utcNow()) | ||
| { | ||
| throw new InvalidOperationException("Gallery returned a publishing key with a missing or expired timestamp."); | ||
| } | ||
|
|
||
| return result; | ||
| } | ||
| } | ||
|
|
||
| internal static PublishingContext GetContext(TestSettings settings) | ||
| { | ||
| if (settings == null) { throw new ArgumentNullException(nameof(settings)); } | ||
| var match = Regex.Match(settings.ConfigurationName ?? string.Empty, | ||
| @"\A(Dev|Int|Prod)(?:-[A-Za-z0-9][A-Za-z0-9_-]*)?\z", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); | ||
|
agr marked this conversation as resolved.
Outdated
|
||
| if (!match.Success) | ||
| { | ||
| throw new InvalidOperationException("E2E trusted publishing requires a Dev, Int, or Prod configuration."); | ||
| } | ||
| if (string.IsNullOrWhiteSpace(settings.TestAccountOwner)) | ||
| { | ||
| throw new InvalidOperationException("E2E trusted publishing requires a non-empty policy username."); | ||
| } | ||
|
|
||
| // Resource and destination allowlist come from NuGet.Services deployment configuration. | ||
| var publishing = settings.TrustedPublishing; | ||
| if (publishing == null || | ||
| !string.Equals(publishing.Environment, match.Groups[1].Value, StringComparison.OrdinalIgnoreCase) || | ||
| !TryGetHttpsRootUri(publishing.ResourceUri, out _) || | ||
| publishing.AllowedGalleryHosts == null || publishing.AllowedGalleryHosts.Length == 0 || | ||
| publishing.AllowedGalleryHosts.Any(host => Uri.CheckHostName(host) != UriHostNameType.Dns)) | ||
| { | ||
| throw new InvalidOperationException("E2E trusted publishing requires deployment configuration with a matching environment, HTTPS resource URI, and approved Gallery hosts."); | ||
| } | ||
|
|
||
| var baseUrl = settings.GalleryConfiguration?.GetServiceBaseUrl(); | ||
| if (!TryGetHttpsRootUri(baseUrl, out var gallery) || | ||
| !publishing.AllowedGalleryHosts.Contains(gallery.Host, StringComparer.OrdinalIgnoreCase)) | ||
| { | ||
| throw new InvalidOperationException("E2E trusted publishing requires an approved HTTPS Gallery root URL for the configuration environment."); | ||
| } | ||
|
|
||
| // Keep the configured resource spelling; Uri.AbsoluteUri would append a slash. | ||
| return new PublishingContext(publishing.ResourceUri, gallery); | ||
| } | ||
|
|
||
| private static bool TryGetHttpsRootUri(string value, out Uri uri) | ||
| { | ||
| return Uri.TryCreate(value, UriKind.Absolute, out uri) && | ||
| uri.Scheme == Uri.UriSchemeHttps && uri.IsDefaultPort && | ||
| string.IsNullOrEmpty(uri.UserInfo) && string.IsNullOrEmpty(uri.Query) && | ||
| string.IsNullOrEmpty(uri.Fragment) && uri.AbsolutePath == "/"; | ||
| } | ||
|
|
||
| private static TokenCredential CreateCredential(string clientId) | ||
| { | ||
| var options = new TokenCredentialOptions(); | ||
| options.Retry.MaxRetries = 2; | ||
| options.Retry.NetworkTimeout = TimeSpan.FromSeconds(20); | ||
| options.Diagnostics.IsLoggingContentEnabled = false; | ||
| return new ManagedIdentityCredential(clientId, options); | ||
| } | ||
|
|
||
| private static HttpClient CreateHttpClient() | ||
| { | ||
| return new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) | ||
| { | ||
| Timeout = TimeSpan.FromSeconds(20) | ||
| }; | ||
| } | ||
|
|
||
| internal sealed class PublishingKey | ||
|
agr marked this conversation as resolved.
Outdated
|
||
| { | ||
| public string TokenType { get; set; } | ||
| public string ApiKey { get; set; } | ||
| public DateTimeOffset? Expires { get; set; } | ||
| } | ||
|
|
||
| internal sealed class PublishingContext | ||
| { | ||
| internal PublishingContext(string resourceUri, Uri galleryUri) | ||
| { | ||
| ResourceUri = resourceUri; | ||
| GalleryUri = galleryUri; | ||
| } | ||
|
|
||
| internal string ResourceUri { get; } | ||
| internal Uri GalleryUri { get; } | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.