Skip to content

Commit

Permalink
azure-repos: fix org name in userinfo (git-ecosystem#1522)
Browse files Browse the repository at this point in the history
Fix a bug in the Azure Repos host provider that prevented the Azure
DevOps organisation name from being pulled from the userinfo part of the
remote URL.

When creating the remote URL from Git input in multiple places we had
not been preserving the userinfo part that was subsequently passed to
the `CreateOrganizationUri` helper method to extract the org URL.

Also add an additional test for PAT mode to cover this use case.

Fixes git-ecosystem#1520
  • Loading branch information
mjcheetham committed Feb 22, 2024
2 parents 541712a + 4041a64 commit e51e1a4
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -239,17 +239,14 @@ public async Task AzureReposProvider_GetCredentialAsync_JwtMode_CachedAuthority_
[Fact]
public async Task AzureReposProvider_GetCredentialAsync_JwtMode_CachedAuthority_DevAzureUrlOrgName_ReturnsCredential()
{

var input = new InputArguments(new Dictionary<string, string>
{
["protocol"] = "https",
["host"] = "dev.azure.com",
["path"] = "org/project/_git/repo",
["username"] = "org"
});

var expectedOrgUri = new Uri("https://dev.azure.com/org");
var remoteUri = new Uri("https://dev.azure.com/org/project/_git/repo");
var authorityUrl = "https://login.microsoftonline.com/common";
var expectedClientId = AzureDevOpsConstants.AadClientId;
var expectedRedirectUri = AzureDevOpsConstants.AadRedirectUri;
Expand Down Expand Up @@ -385,7 +382,6 @@ public async Task AzureReposProvider_GetCredentialAsync_JwtMode_CachedAuthority_
[Fact]
public async Task AzureReposProvider_GetCredentialAsync_JwtMode_NoCachedAuthority_NoUser_ReturnsCredential()
{

var input = new InputArguments(new Dictionary<string, string>
{
["protocol"] = "https",
Expand Down Expand Up @@ -433,9 +429,52 @@ public async Task AzureReposProvider_GetCredentialAsync_JwtMode_NoCachedAuthorit
}

[Fact]
public async Task AzureReposProvider_GetCredentialAsync_PatMode_NoExistingPat_GeneratesCredential()
public async Task AzureReposProvider_GetCredentialAsync_PatMode_OrgInUserName_NoExistingPat_GeneratesCredential()
{
var input = new InputArguments(new Dictionary<string, string>
{
["protocol"] = "https",
["host"] = "dev.azure.com",
["username"] = "org"
});

var expectedOrgUri = new Uri("https://dev.azure.com/org");
var authorityUrl = "https://login.microsoftonline.com/common";
var expectedClientId = AzureDevOpsConstants.AadClientId;
var expectedRedirectUri = AzureDevOpsConstants.AadRedirectUri;
var expectedScopes = AzureDevOpsConstants.AzureDevOpsDefaultScopes;
var accessToken = "ACCESS-TOKEN";
var personalAccessToken = "PERSONAL-ACCESS-TOKEN";
var account = "john.doe";
var authResult = CreateAuthResult(account, accessToken);

var context = new TestCommandContext();

var azDevOpsMock = new Mock<IAzureDevOpsRestApi>(MockBehavior.Strict);
azDevOpsMock.Setup(x => x.GetAuthorityAsync(expectedOrgUri)).ReturnsAsync(authorityUrl);
azDevOpsMock.Setup(x => x.CreatePersonalAccessTokenAsync(expectedOrgUri, accessToken, It.IsAny<IEnumerable<string>>()))
.ReturnsAsync(personalAccessToken);

var msAuthMock = new Mock<IMicrosoftAuthentication>(MockBehavior.Strict);
msAuthMock.Setup(x => x.GetTokenForUserAsync(authorityUrl, expectedClientId, expectedRedirectUri, expectedScopes, null, true))
.ReturnsAsync(authResult);

var authorityCacheMock = new Mock<IAzureDevOpsAuthorityCache>(MockBehavior.Strict);

var userMgrMock = new Mock<IAzureReposBindingManager>(MockBehavior.Strict);

var provider = new AzureReposHostProvider(context, azDevOpsMock.Object, msAuthMock.Object, authorityCacheMock.Object, userMgrMock.Object);

ICredential credential = await provider.GetCredentialAsync(input);

Assert.NotNull(credential);
Assert.Equal(account, credential.Account);
Assert.Equal(personalAccessToken, credential.Password);
}

[Fact]
public async Task AzureReposProvider_GetCredentialAsync_PatMode_NoExistingPat_GeneratesCredential()
{
var input = new InputArguments(new Dictionary<string, string>
{
["protocol"] = "https",
Expand Down
20 changes: 10 additions & 10 deletions src/shared/Microsoft.AzureRepos/AzureReposHostProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,8 @@ public async Task<ICredential> GetCredentialAsync(InputArguments input)

if (UsePersonalAccessTokens())
{
Uri remoteUri = input.GetRemoteUri();
string service = GetServiceName(remoteUri);
Uri remoteWithUserUri = input.GetRemoteUri(includeUser: true);
string service = GetServiceName(remoteWithUserUri);
string account = GetAccountNameForCredentialQuery(input);

_context.Trace.WriteLine($"Looking for existing credential in store with service={service} account={account}...");
Expand Down Expand Up @@ -219,8 +219,8 @@ private async Task<ICredential> GeneratePersonalAccessTokenAsync(InputArguments
"Unencrypted HTTP is not supported for Azure Repos. Ensure the repository remote URL is using HTTPS.");
}

Uri remoteUri = input.GetRemoteUri();
Uri orgUri = UriHelpers.CreateOrganizationUri(remoteUri, out _);
Uri remoteUserUri = input.GetRemoteUri(includeUser: true);
Uri orgUri = UriHelpers.CreateOrganizationUri(remoteUserUri, out _);

// Determine the MS authentication authority for this organization
_context.Trace.WriteLine("Determining Microsoft Authentication Authority...");
Expand Down Expand Up @@ -257,17 +257,17 @@ private async Task<ICredential> GeneratePersonalAccessTokenAsync(InputArguments

private async Task<IMicrosoftAuthenticationResult> GetAzureAccessTokenAsync(InputArguments input)
{
Uri remoteUri = input.GetRemoteUri();
Uri remoteWithUserUri = input.GetRemoteUri(includeUser: true);
string userName = input.UserName;

// We should not allow unencrypted communication and should inform the user
if (StringComparer.OrdinalIgnoreCase.Equals(remoteUri.Scheme, "http"))
if (StringComparer.OrdinalIgnoreCase.Equals(remoteWithUserUri.Scheme, "http"))
{
throw new Trace2Exception(_context.Trace2,
"Unencrypted HTTP is not supported for Azure Repos. Ensure the repository remote URL is using HTTPS.");
}

Uri orgUri = UriHelpers.CreateOrganizationUri(remoteUri, out string orgName);
Uri orgUri = UriHelpers.CreateOrganizationUri(remoteWithUserUri, out string orgName);

_context.Trace.WriteLine($"Determining Microsoft Authentication authority for Azure DevOps organization '{orgName}'...");
if (TryGetAuthorityFromHeaders(input.WwwAuth, out string authAuthority))
Expand Down Expand Up @@ -306,8 +306,8 @@ private async Task<IMicrosoftAuthenticationResult> GetAzureAccessTokenAsync(Inpu
//
var icmp = StringComparer.OrdinalIgnoreCase;
if (!string.IsNullOrWhiteSpace(userName) &&
(UriHelpers.IsVisualStudioComHost(remoteUri.Host) ||
(UriHelpers.IsAzureDevOpsHost(remoteUri.Host) && !icmp.Equals(orgName, userName))))
(UriHelpers.IsVisualStudioComHost(remoteWithUserUri.Host) ||
(UriHelpers.IsAzureDevOpsHost(remoteWithUserUri.Host) && !icmp.Equals(orgName, userName))))
{
_context.Trace.WriteLine("Using username as specified in remote.");
}
Expand Down Expand Up @@ -422,7 +422,7 @@ private static string GetServiceName(Uri remoteUri)
{
// If we're given the full path for an older *.visualstudio.com-style URL then we should
// respect that in the service name.
return remoteUri.AbsoluteUri.TrimEnd('/');
return remoteUri.WithoutUserInfo().AbsoluteUri.TrimEnd('/');
}

throw new InvalidOperationException("Host is not Azure DevOps.");
Expand Down

0 comments on commit e51e1a4

Please sign in to comment.