Skip to content

Commit 018774a

Browse files
authored
Port relevant commits from 2.9.0 and 2.9.1 releases (#2382)
This is a port of commits from the 2.9.0 and 2.9.1 embargoed releases into the vnext branch. Note that not all of the commits were required since `vnext` already had some of the bug fixes (the CFS release change), or have been superseded by refactoring (`MicrosoftAuthentication -> EntraAuthentication` already changed how we use redirect URIs and resolved auth flows) and updates to even newer MSAL versions.
2 parents 90f1454 + 329da7f commit 018774a

17 files changed

Lines changed: 506 additions & 45 deletions

‎docs/generic-oauth.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ following values in your Git configuration:
4242
- Client Secret (optional)
4343
- Redirect URL (optional, defaults to `http://127.0.0.1`)
4444
- Scopes (optional)
45+
- Response Mode (optional, defaults to `query`)
4546
- OAuth Endpoints
4647
- Authorization Endpoint
4748
- Token Endpoint
@@ -62,6 +63,7 @@ git config --global credential.<HOST>.oauthAuthorizeEndpoint <AuthEndpoint>
6263
git config --global credential.<HOST>.oauthTokenEndpoint <TokenEndpoint>
6364
git config --global credential.<HOST>.oauthScopes <Scopes>
6465
git config --global credential.<HOST>.oauthDeviceEndpoint <DeviceEndpoint>
66+
git config --global credential.<HOST>.oauthResponseMode <ResponseMode>
6567
```
6668

6769
**Example commands:**
@@ -83,13 +85,35 @@ git config --global credential.<HOST>.oauthDeviceEndpoint <DeviceEndpoint>
8385
oauthScopes = "code:write profile:read"
8486
oauthDefaultUserName = "OAUTH"
8587
oauthUseClientAuthHeader = false
88+
oauthResponseMode = "query"
8689
```
8790

8891
### Additional configuration
8992

9093
Depending on the specific implementation of OAuth with your Git host you may
9194
also need to specify additional behavior.
9295

96+
#### Response mode
97+
98+
The response mode controls how the authorization server returns the response to
99+
the loopback redirect URI once the user has authenticated. GCM supports the
100+
following values:
101+
102+
- `query` (default) - parameters are returned in the redirect URI query string.
103+
- `fragment` - parameters are returned in the redirect URI fragment.
104+
- `form_post` - parameters are returned as an auto-submitting HTML form that is
105+
POSTed to the redirect URI, as described by the
106+
[OAuth 2.0 Form Post Response Mode][form-post-spec] specification.
107+
108+
Most hosts use the default `query` mode. Only set this if your host requires a
109+
specific response mode:
110+
111+
```shell
112+
git config --global credential.<HOST>.oauthResponseMode <query|fragment|form_post>
113+
```
114+
115+
[form-post-spec]: https://openid.net/specs/oauth-v2-form-post-response-mode-1_0.html
116+
93117
#### Token user name
94118

95119
If your Git host requires that you specify a username to use with OAuth tokens

‎src/Atlassian.Bitbucket.Tests/Cloud/BitbucketOAuth2ClientTest.cs‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public async Task BitbucketOAuth2Client_GetAuthorizationCodeAsync_ReturnsCode()
3636

3737
Bitbucket.Cloud.BitbucketOAuth2Client client = GetBitbucketOAuth2Client();
3838

39-
MockGetAuthenticationCodeAsync(finalCallbackUri, null, client.Scopes);
39+
MockGetAuthenticationResponseAsync(finalCallbackUri, null, client.Scopes);
4040

4141
MockCodeGenerator();
4242

@@ -56,7 +56,7 @@ public async Task BitbucketOAuth2Client_GetAuthorizationCodeAsync_RespectsClient
5656

5757
Bitbucket.Cloud.BitbucketOAuth2Client client = GetBitbucketOAuth2Client();
5858

59-
MockGetAuthenticationCodeAsync(finalCallbackUri, clientId, client.Scopes);
59+
MockGetAuthenticationResponseAsync(finalCallbackUri, clientId, client.Scopes);
6060

6161
MockCodeGenerator();
6262

@@ -115,7 +115,7 @@ private void MockCodeGenerator()
115115
codeGenerator.Setup(c => c.CreatePkceCodeChallenge(OAuth2PkceChallengeMethod.Sha256, pkceCodeVerifier)).Returns(pkceCodeChallenge);
116116
}
117117

118-
private void MockGetAuthenticationCodeAsync(Uri finalCallbackUri, string overrideClientId, IEnumerable<string> scopes)
118+
private void MockGetAuthenticationResponseAsync(Uri finalCallbackUri, string overrideClientId, IEnumerable<string> scopes)
119119
{
120120
var authorizationUri = new UriBuilder(CloudConstants.OAuth2AuthorizationEndpoint)
121121
{
@@ -128,7 +128,8 @@ private void MockGetAuthenticationCodeAsync(Uri finalCallbackUri, string overrid
128128
+ "&scope=" + WebUtility.UrlEncode(string.Join(" ", scopes)).ToLower()
129129
}.Uri;
130130

131-
browser.Setup(b => b.GetAuthenticationCodeAsync(authorizationUri, rootCallbackUri, ct)).Returns(Task.FromResult(finalCallbackUri));
131+
browser.Setup(b => b.GetAuthenticationResponseAsync(authorizationUri, rootCallbackUri, OAuth2ResponseMode.Default, ct))
132+
.Returns(Task.FromResult(finalCallbackUri.GetQueryParameters()));
132133
}
133134

134135
private Uri MockFinalCallbackUri()

‎src/Atlassian.Bitbucket.Tests/DataCenter/BitbucketOAuth2ClientTest.cs‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ public async Task BitbucketOAuth2Client_GetAuthorizationCodeAsync_ReturnsCode()
3737

3838
var client = GetBitbucketOAuth2Client();
3939

40-
MockGetAuthenticationCodeAsync(remoteUrl, rootCallbackUri, finalCallbackUri, clientId, client.Scopes);
40+
MockGetAuthenticationResponseAsync(remoteUrl, rootCallbackUri, finalCallbackUri, clientId, client.Scopes);
4141

4242
MockCodeGenerator();
4343

@@ -58,7 +58,7 @@ public async Task BitbucketOAuth2Client_GetAuthorizationCodeAsync_ReturnsCode_Wh
5858

5959
var client = GetBitbucketOAuth2Client();
6060

61-
MockGetAuthenticationCodeAsync(remoteUrl, new Uri(rootCallbackUrl), finalCallbackUri, clientId, client.Scopes);
61+
MockGetAuthenticationResponseAsync(remoteUrl, new Uri(rootCallbackUrl), finalCallbackUri, clientId, client.Scopes);
6262

6363
MockCodeGenerator();
6464

@@ -90,7 +90,7 @@ private void MockCodeGenerator()
9090
codeGenerator.Setup(c => c.CreatePkceCodeChallenge(OAuth2PkceChallengeMethod.Sha256, pkceCodeVerifier)).Returns(pkceCodeChallenge);
9191
}
9292

93-
private void MockGetAuthenticationCodeAsync(string url, Uri redirectUri, Uri finalCallbackUri, string overrideClientId, IEnumerable<string> scopes)
93+
private void MockGetAuthenticationResponseAsync(string url, Uri redirectUri, Uri finalCallbackUri, string overrideClientId, IEnumerable<string> scopes)
9494
{
9595
var authorizationUri = new UriBuilder(url + "/rest/oauth2/latest/authorize")
9696
{
@@ -103,7 +103,8 @@ private void MockGetAuthenticationCodeAsync(string url, Uri redirectUri, Uri fin
103103
+ "&scope=" + WebUtility.UrlEncode(string.Join(" ", scopes)).ToUpper()
104104
}.Uri;
105105

106-
browser.Setup(b => b.GetAuthenticationCodeAsync(authorizationUri, redirectUri, ct)).Returns(Task.FromResult(finalCallbackUri));
106+
browser.Setup(b => b.GetAuthenticationResponseAsync(authorizationUri, redirectUri, OAuth2ResponseMode.Default, ct))
107+
.Returns(Task.FromResult(finalCallbackUri.GetQueryParameters()));
107108
}
108109

109110
private Uri MockFinalCallbackUri(Uri redirectUri)

‎src/Core.Tests/Authentication/OAuth2ClientTests.cs‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,89 @@ await Assert.ThrowsAsync<ArgumentException>(() =>
174174
client.GetAuthorizationCodeAsync(expectedScopes, browser, extraParams, CancellationToken.None));
175175
}
176176

177+
[Theory]
178+
[InlineData(OAuth2ResponseMode.Query, "query")]
179+
[InlineData(OAuth2ResponseMode.Fragment, "fragment")]
180+
[InlineData(OAuth2ResponseMode.FormPost, "form_post")]
181+
public async Task OAuth2Client_GetAuthorizationCodeAsync_NonDefaultResponseMode_SendsResponseModeParameter(
182+
OAuth2ResponseMode responseMode, string expectedValue)
183+
{
184+
const string expectedAuthCode = "68c39cbd8d";
185+
186+
var baseUri = new Uri("https://example.com");
187+
OAuth2ServerEndpoints endpoints = CreateEndpoints(baseUri);
188+
189+
var httpHandler = new TestHttpMessageHandler {ThrowOnUnexpectedRequest = true};
190+
191+
string[] expectedScopes = {"read", "write", "delete"};
192+
193+
OAuth2Application app = CreateTestApplication();
194+
195+
var server = new TestOAuth2Server(endpoints);
196+
server.RegisterApplication(app);
197+
server.Bind(httpHandler);
198+
server.TokenGenerator.AuthCodes.Add(expectedAuthCode);
199+
200+
server.AuthorizationEndpointInvoked += (_, request) =>
201+
{
202+
IDictionary<string, string> actualParams = request.RequestUri.GetQueryParameters();
203+
Assert.True(actualParams.TryGetValue(
204+
OAuth2Constants.AuthorizationEndpoint.ResponseModeParameter, out string actualMode));
205+
Assert.Equal(expectedValue, actualMode);
206+
};
207+
208+
IOAuth2WebBrowser browser = new TestOAuth2WebBrowser(httpHandler);
209+
210+
var trace2 = new NullTrace2();
211+
OAuth2Client client = new OAuth2Client(
212+
new HttpClient(httpHandler), endpoints, TestClientId, trace2,
213+
TestRedirectUri, TestClientSecret, responseMode: responseMode);
214+
215+
OAuth2AuthorizationCodeResult result = await client.GetAuthorizationCodeAsync(
216+
expectedScopes, browser, null, CancellationToken.None);
217+
218+
Assert.Equal(expectedAuthCode, result.Code);
219+
}
220+
221+
[Fact]
222+
public async Task OAuth2Client_GetAuthorizationCodeAsync_DefaultResponseMode_OmitsResponseModeParameter()
223+
{
224+
const string expectedAuthCode = "68c39cbd8d";
225+
226+
var baseUri = new Uri("https://example.com");
227+
OAuth2ServerEndpoints endpoints = CreateEndpoints(baseUri);
228+
229+
var httpHandler = new TestHttpMessageHandler {ThrowOnUnexpectedRequest = true};
230+
231+
string[] expectedScopes = {"read", "write", "delete"};
232+
233+
OAuth2Application app = CreateTestApplication();
234+
235+
var server = new TestOAuth2Server(endpoints);
236+
server.RegisterApplication(app);
237+
server.Bind(httpHandler);
238+
server.TokenGenerator.AuthCodes.Add(expectedAuthCode);
239+
240+
server.AuthorizationEndpointInvoked += (_, request) =>
241+
{
242+
IDictionary<string, string> actualParams = request.RequestUri.GetQueryParameters();
243+
Assert.False(actualParams.ContainsKey(
244+
OAuth2Constants.AuthorizationEndpoint.ResponseModeParameter));
245+
};
246+
247+
IOAuth2WebBrowser browser = new TestOAuth2WebBrowser(httpHandler);
248+
249+
var trace2 = new NullTrace2();
250+
OAuth2Client client = new OAuth2Client(
251+
new HttpClient(httpHandler), endpoints, TestClientId, trace2,
252+
TestRedirectUri, TestClientSecret, responseMode: OAuth2ResponseMode.Default);
253+
254+
OAuth2AuthorizationCodeResult result = await client.GetAuthorizationCodeAsync(
255+
expectedScopes, browser, null, CancellationToken.None);
256+
257+
Assert.Equal(expectedAuthCode, result.Code);
258+
}
259+
177260
[Fact]
178261
public async Task OAuth2Client_GetDeviceCodeAsync()
179262
{
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
using GitCredentialManager.Authentication.OAuth;
2+
using Xunit;
3+
4+
namespace GitCredentialManager.Tests.Authentication;
5+
6+
public class OAuth2ResponseModeTests
7+
{
8+
[Theory]
9+
[InlineData(OAuth2ResponseMode.Default, null)]
10+
[InlineData(OAuth2ResponseMode.Query, "query")]
11+
[InlineData(OAuth2ResponseMode.Fragment, "fragment")]
12+
[InlineData(OAuth2ResponseMode.FormPost, "form_post")]
13+
public void OAuth2ResponseMode_GetParameterValue(OAuth2ResponseMode mode, string expected)
14+
{
15+
Assert.Equal(expected, mode.GetParameterValue());
16+
}
17+
18+
[Theory]
19+
[InlineData("query", OAuth2ResponseMode.Query)]
20+
[InlineData("Query", OAuth2ResponseMode.Query)]
21+
[InlineData("fragment", OAuth2ResponseMode.Fragment)]
22+
[InlineData("FRAGMENT", OAuth2ResponseMode.Fragment)]
23+
[InlineData("form_post", OAuth2ResponseMode.FormPost)]
24+
[InlineData("FORM_POST", OAuth2ResponseMode.FormPost)]
25+
[InlineData("formpost", OAuth2ResponseMode.FormPost)]
26+
public void OAuth2ResponseMode_TryParse_Valid(string value, OAuth2ResponseMode expected)
27+
{
28+
Assert.True(OAuth2ResponseModeExtensions.TryParse(value, out OAuth2ResponseMode actual));
29+
Assert.Equal(expected, actual);
30+
}
31+
32+
[Theory]
33+
[InlineData(null)]
34+
[InlineData("")]
35+
[InlineData(" ")]
36+
[InlineData("web_message")]
37+
[InlineData("unknown")]
38+
public void OAuth2ResponseMode_TryParse_Invalid_ReturnsFalse(string value)
39+
{
40+
Assert.False(OAuth2ResponseModeExtensions.TryParse(value, out _));
41+
}
42+
}

‎src/Core.Tests/Authentication/OAuth2SystemWebBrowserTests.cs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,4 +63,20 @@ public void OAuth2SystemWebBrowser_UpdateRedirectUri_AnyPort(string input)
6363
);
6464
Assert.False(actualUri.IsDefaultPort);
6565
}
66+
67+
[Theory]
68+
[InlineData("application/x-www-form-urlencoded", true)]
69+
[InlineData("application/x-www-form-urlencoded; charset=utf-8", true)]
70+
[InlineData("application/x-www-form-urlencoded;charset=UTF-8", true)]
71+
[InlineData("APPLICATION/X-WWW-FORM-URLENCODED", true)]
72+
[InlineData(" application/x-www-form-urlencoded ; charset=utf-8 ", true)]
73+
[InlineData("application/json", false)]
74+
[InlineData("text/plain; charset=utf-8", false)]
75+
[InlineData("multipart/form-data; boundary=----abc", false)]
76+
[InlineData("", false)]
77+
[InlineData(null, false)]
78+
public void OAuth2SystemWebBrowser_IsFormUrlEncoded(string contentType, bool expected)
79+
{
80+
Assert.Equal(expected, OAuth2SystemWebBrowser.IsFormUrlEncoded(contentType));
81+
}
6682
}

‎src/Core.Tests/GenericOAuthConfigTests.cs‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Collections.Generic;
3+
using GitCredentialManager.Authentication.OAuth;
34
using GitCredentialManager.Tests.Objects;
45
using Xunit;
56

@@ -99,5 +100,75 @@ public void GenericOAuthConfig_TryGet_Gitea()
99100
Assert.Equal(expectedAuthzEndpoint, config.Endpoints.AuthorizationEndpoint);
100101
Assert.Equal(expectedTokenEndpoint, config.Endpoints.TokenEndpoint);
101102
}
103+
104+
[Theory]
105+
[InlineData("query", OAuth2ResponseMode.Query)]
106+
[InlineData("fragment", OAuth2ResponseMode.Fragment)]
107+
[InlineData("form_post", OAuth2ResponseMode.FormPost)]
108+
[InlineData("FORM_POST", OAuth2ResponseMode.FormPost)]
109+
public void GenericOAuthConfig_TryGet_ParsesResponseMode(string value, OAuth2ResponseMode expected)
110+
{
111+
bool result = TryGetWithResponseMode(value, out GenericOAuthConfig config);
112+
113+
Assert.True(result);
114+
Assert.Equal(expected, config.ResponseMode);
115+
}
116+
117+
[Fact]
118+
public void GenericOAuthConfig_TryGet_InvalidResponseMode_FallsBackToDefault()
119+
{
120+
bool result = TryGetWithResponseMode("bogus", out GenericOAuthConfig config);
121+
122+
Assert.True(result);
123+
Assert.Equal(OAuth2ResponseMode.Default, config.ResponseMode);
124+
}
125+
126+
[Fact]
127+
public void GenericOAuthConfig_TryGet_ResponseModeUnset_UsesDefault()
128+
{
129+
bool result = TryGetWithResponseMode(null, out GenericOAuthConfig config);
130+
131+
Assert.True(result);
132+
Assert.Equal(OAuth2ResponseMode.Default, config.ResponseMode);
133+
}
134+
135+
private static bool TryGetWithResponseMode(string responseMode, out GenericOAuthConfig config)
136+
{
137+
const string protocol = "https";
138+
const string host = "example.com";
139+
var remoteUri = new Uri($"{protocol}://{host}");
140+
141+
string GetKey(string name) => $"{Constants.GitConfiguration.Credential.SectionName}.https://example.com.{name}";
142+
143+
var trace = new NullTrace();
144+
var gitConfig = new TestGitConfiguration
145+
{
146+
Global =
147+
{
148+
[GetKey(Constants.GitConfiguration.Credential.OAuthClientId)] = new[] { "client-id" },
149+
[GetKey(Constants.GitConfiguration.Credential.OAuthAuthzEndpoint)] = new[] { "/oauth/authorize" },
150+
[GetKey(Constants.GitConfiguration.Credential.OAuthTokenEndpoint)] = new[] { "/oauth/token" },
151+
}
152+
};
153+
154+
if (responseMode != null)
155+
{
156+
gitConfig.Global[GetKey(Constants.GitConfiguration.Credential.OAuthResponseMode)] = new[] { responseMode };
157+
}
158+
159+
var settings = new TestSettings
160+
{
161+
GitConfiguration = gitConfig,
162+
RemoteUri = remoteUri
163+
};
164+
165+
var input = new GitRequest(new Dictionary<string, string>
166+
{
167+
{"protocol", protocol},
168+
{"host", host},
169+
});
170+
171+
return GenericOAuthConfig.TryGet(trace, settings, input, out config);
172+
}
102173
}
103174
}
Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
using System;
2-
using System.Net;
2+
using System.Collections.Generic;
33
using System.Threading;
44
using System.Threading.Tasks;
55

@@ -9,6 +9,16 @@ public interface IOAuth2WebBrowser
99
{
1010
Uri UpdateRedirectUri(Uri uri);
1111

12-
Task<Uri> GetAuthenticationCodeAsync(Uri authorizationUri, Uri redirectUri, CancellationToken ct);
12+
/// <summary>
13+
/// Drive the user agent through the authorization request and intercept the
14+
/// authorization response delivered to the redirect URI.
15+
/// </summary>
16+
/// <param name="authorizationUri">Authorization request URI to open in the user agent.</param>
17+
/// <param name="redirectUri">Redirect URI to intercept the response on.</param>
18+
/// <param name="responseMode">Mechanism the authorization server uses to deliver the response.</param>
19+
/// <param name="ct">Token to cancel the operation.</param>
20+
/// <returns>The authorization response parameters.</returns>
21+
Task<IDictionary<string, string>> GetAuthenticationResponseAsync(
22+
Uri authorizationUri, Uri redirectUri, OAuth2ResponseMode responseMode, CancellationToken ct);
1323
}
1424
}

0 commit comments

Comments
 (0)