Skip to content

Commit 9c3b25d

Browse files
authored
protocol: add support for 'authtype' capability (#2457)
switch to alternative credential properties for 'authtype' add support for 'ephemeral' state to protocol and basic credential interface
2 parents 5344748 + 36f4624 commit 9c3b25d

9 files changed

Lines changed: 161 additions & 20 deletions

File tree

‎src/Core.Tests/Commands/CapabilityCommandTests.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ public void CapabilityCommand_Execute_WritesVersionAndAdvertisedCapabilities()
2222
Assert.StartsWith("version 0\n", actualOutput);
2323

2424
// GCM advertises the state capability.
25-
Assert.Equal("version 0\ncapability state\n", actualOutput);
25+
Assert.Equal("version 0\ncapability state\ncapability authtype\n", actualOutput);
2626
}
2727

2828
[Fact]

‎src/Core.Tests/Commands/GetCommandTests.cs‎

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ public async Task GetCommand_ExecuteAsync_NegotiatedCapability_EchoesIntersectio
122122
string actualOutput = context.Streams.Out.ToString().Replace("\r\n", "\n");
123123

124124
Assert.Contains("capability[]=state\n", actualOutput);
125-
Assert.DoesNotContain("capability[]=authtype", actualOutput);
125+
Assert.Contains("capability[]=authtype\n", actualOutput);
126126
}
127127

128128
[Fact]
@@ -328,6 +328,62 @@ public async Task GetCommand_ExecuteAsync_OutputOrdering_CapabilitiesFirstThenSc
328328
"state[] must follow continue=1");
329329
}
330330

331+
[Fact]
332+
public async Task GetCommand_ExecuteAsync_CapabilityAuthType_MissingRevertsToPlainPassword()
333+
{
334+
ICredential testCredential = new GitCredential("alice", "hunter2");
335+
var response = GitResponse.Ok(testCredential, isEphemeral: true, authtype: "token");
336+
337+
var stdin = "protocol=https\nhost=example.com\n\n";
338+
339+
var providerMock = new Mock<IHostProvider>();
340+
providerMock.Setup(x => x.GetCredentialAsync(It.IsAny<GitRequest>()))
341+
.ReturnsAsync(response);
342+
var providerRegistry = new TestHostProviderRegistry { Provider = providerMock.Object };
343+
var context = new TestCommandContext { Streams = { In = stdin } };
344+
345+
var command = new GetCommand(context, providerRegistry);
346+
347+
await command.ExecuteAsync();
348+
349+
string[] actualOutput = context.Streams.Out.ToString().Replace("\r\n", "\n").Split('\n');
350+
351+
// Emits regular Credential without 'state[]=authtype' support.
352+
Assert.Contains("username=alice", actualOutput);
353+
Assert.Contains("password=hunter2", actualOutput);
354+
Assert.DoesNotContain("authtype=token", actualOutput);
355+
Assert.DoesNotContain("credential=hunter2", actualOutput);
356+
Assert.DoesNotContain("ephemeral=1", actualOutput);
357+
}
358+
359+
[Fact]
360+
public async Task GetCommand_ExecuteAsync_CapabilityAuthType_UsesAuthTypeFeatures()
361+
{
362+
ICredential testCredential = new GitCredential("alice", "hunter2");
363+
var response = GitResponse.Ok(testCredential, isEphemeral: true, authtype: "token");
364+
365+
var stdin = "protocol=https\nhost=example.com\ncapability[]=authtype\n\n";
366+
367+
var providerMock = new Mock<IHostProvider>();
368+
providerMock.Setup(x => x.GetCredentialAsync(It.IsAny<GitRequest>()))
369+
.ReturnsAsync(response);
370+
var providerRegistry = new TestHostProviderRegistry { Provider = providerMock.Object };
371+
var context = new TestCommandContext { Streams = { In = stdin } };
372+
373+
var command = new GetCommand(context, providerRegistry);
374+
375+
await command.ExecuteAsync();
376+
377+
string[] actualOutput = context.Streams.Out.ToString().Replace("\r\n", "\n").Split('\n');
378+
379+
// Ephemeral credential with 'authtype' and 'credential' value
380+
Assert.DoesNotContain("username=alice", actualOutput);
381+
Assert.DoesNotContain("password=hunter2", actualOutput);
382+
Assert.Contains("authtype=token", actualOutput);
383+
Assert.Contains("credential=hunter2", actualOutput);
384+
Assert.Contains("ephemeral=1", actualOutput);
385+
}
386+
331387
#region Helpers
332388

333389
private static IDictionary<string, string> ParseDictionary(StringBuilder sb) => ParseDictionary(sb.ToString());

‎src/Core/Commands/GetCommand.cs‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ protected override async Task ExecuteInternalAsync(GitRequest request, IHostProv
5959
// Negotiate capabilities by intersecting what Git advertised with what GCM supports.
6060
// Capability-gated output fields may only be emitted for capabilities in this set.
6161
GitCapabilities negotiated = request.Capabilities & Constants.SupportedCapabilities;
62+
bool authTypeCapNegotiated = (negotiated & GitCapabilities.AuthType) != 0;
6263
bool stateCapNegotiated = (negotiated & GitCapabilities.State) != 0;
6364

6465
Context.Trace.WriteLine($"Git capability: {request.Capabilities}");
@@ -98,10 +99,26 @@ protected override async Task ExecuteInternalAsync(GitRequest request, IHostProv
9899
//
99100
// Credential
100101
//
101-
stdout.WriteLine($"username={credential.Account}");
102-
Context.Trace.WriteLine($"\tusername={credential.Account}");
103-
stdout.WriteLine($"password={credential.Password}");
104-
Context.Trace.WriteLineSecrets("\tpassword={0}", new object[] { credential.Password });
102+
var authtype = response.AuthType;
103+
if (authTypeCapNegotiated && authtype is not null)
104+
{
105+
stdout.WriteLine($"{Constants.CredentialProtocol.AuthTypeKey}={authtype}");
106+
Context.Trace.WriteLine($"\t{Constants.CredentialProtocol.AuthTypeKey}={authtype}");
107+
stdout.WriteLine($"{Constants.CredentialProtocol.CredentialKey}={credential.Password}");
108+
Context.Trace.WriteLineSecrets("\t" + Constants.CredentialProtocol.CredentialKey + "={0}", [credential.Password]);
109+
}
110+
else
111+
{
112+
stdout.WriteLine($"{Constants.CredentialProtocol.UserNameKey}={credential.Account}");
113+
Context.Trace.WriteLine($"\t{Constants.CredentialProtocol.UserNameKey}={credential.Account}");
114+
stdout.WriteLine($"{Constants.CredentialProtocol.PasswordKey}={credential.Password}");
115+
Context.Trace.WriteLineSecrets("\t" + Constants.CredentialProtocol.PasswordKey + "={0}", [ credential.Password ]);
116+
}
117+
if (authTypeCapNegotiated && response.IsCredentialEphemeral)
118+
{
119+
stdout.WriteLine($"{Constants.CredentialProtocol.EphemeralKey}=1");
120+
Context.Trace.WriteLine($"\t{Constants.CredentialProtocol.EphemeralKey}=1");
121+
}
105122

106123
//
107124
// Custom additional properties

‎src/Core/Commands/GitCommandBase.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ internal async Task ExecuteAsync()
5151

5252
// Determine the host provider
5353
Context.Trace.WriteLine("Detecting host provider for request:");
54-
Context.Trace.WriteDictionarySecrets(inputDict, new []{ "password" }, StringComparer.OrdinalIgnoreCase);
54+
Context.Trace.WriteDictionarySecrets(inputDict, [ "password", "credential" ], StringComparer.OrdinalIgnoreCase);
5555
IHostProvider provider;
5656
using (Trace2.StartRegion("git_cmd", "resolve_provider"))
5757
{

‎src/Core/Commands/StoreCommand.cs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,16 @@ protected override void EnsureMinimumRequest(GitRequest request)
2424
{
2525
base.EnsureMinimumRequest(request);
2626

27+
// When "authtype" is set, Git uses "credential" field for the secret
28+
if (request.AuthType is not null)
29+
{
30+
if (request.Credential is null)
31+
{
32+
throw new InvalidOperationException("Missing 'credential' request argument");
33+
}
34+
return;
35+
}
36+
2737
// An empty string username/password are valid inputs, so only check for `null` (not provided)
2838
if (request.UserName is null)
2939
{

‎src/Core/Constants.cs‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public static class Constants
3636
/// <summary>
3737
/// The set of Git credential protocol capabilities supported by Git Credential Manager.
3838
/// </summary>
39-
public const GitCapabilities SupportedCapabilities = GitCapabilities.State;
39+
public const GitCapabilities SupportedCapabilities = GitCapabilities.State | GitCapabilities.AuthType;
4040

4141
public static class CredentialProtocol
4242
{
@@ -57,6 +57,36 @@ public static class CredentialProtocol
5757
/// </summary>
5858
public const string ContinueKey = "continue";
5959

60+
/// <summary>
61+
/// The Git credential protocol attribute name carrying alternative
62+
/// HTTP Authorization scheme type.
63+
/// (string, gated by the <c>authtype</c> capability).
64+
/// </summary>
65+
public const string AuthTypeKey = "authtype";
66+
67+
/// <summary>
68+
/// The Git credential protocol attribute name carrying raw credential data.
69+
/// (string, gated by the <c>authtype</c> capability).
70+
/// </summary>
71+
public const string CredentialKey = "credential";
72+
73+
/// <summary>
74+
/// The Git credential protocol attribute name carrying setting
75+
/// for ephemeral credential type.
76+
/// (string, gated by the <c>authtype</c> capability).
77+
/// </summary>
78+
public const string EphemeralKey = "ephemeral";
79+
80+
/// <summary>
81+
/// The Git credential protocol attribute name for password.
82+
/// </summary>
83+
public const string PasswordKey = "password";
84+
85+
/// <summary>
86+
/// The Git credential protocol attribute name for username.
87+
/// </summary>
88+
public const string UserNameKey = "username";
89+
6090
/// <summary>
6191
/// Prefix that Git Credential Manager reserves on every <c>state[]</c> entry
6292
/// so its state can be distinguished from other helpers' state per

‎src/Core/GitCapabilities.cs‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,14 @@ public enum GitCapabilities
3838
/// flag that signals a non-final authentication step is expected.
3939
/// </remarks>
4040
State = 1 << 0,
41+
42+
/// <summary>
43+
/// The <c>authtype</c>, <c>credential</c>, and <c>ephemeral</c> attributes are understood.
44+
/// </summary>
45+
/// <remarks>
46+
/// Provides alternative formats for HTTP Authorization header.
47+
/// </remarks>
48+
AuthType = 1 << 1,
4149
}
4250

4351
/// <summary>
@@ -66,7 +74,8 @@ public static GitCapabilities ParseName(string name)
6674
// handling is implemented.
6775
return name.ToLowerInvariant() switch
6876
{
69-
"state" => GitCapabilities.State,
77+
Constants.CredentialProtocol.StateKey => GitCapabilities.State,
78+
Constants.CredentialProtocol.AuthTypeKey => GitCapabilities.AuthType,
7079
_ => GitCapabilities.None,
7180
};
7281
}
@@ -89,7 +98,8 @@ public static string ToProtocolName(GitCapabilities capability)
8998
// protocol name distinct from its .NET enum name).
9099
return capability switch
91100
{
92-
GitCapabilities.State => "state",
101+
GitCapabilities.State => Constants.CredentialProtocol.StateKey,
102+
GitCapabilities.AuthType => Constants.CredentialProtocol.AuthTypeKey,
93103
GitCapabilities.None => throw new ArgumentException(
94104
"Cannot render the None capability to a protocol name.",
95105
nameof(capability)),

‎src/Core/GitRequest.cs‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,13 @@ public GitRequest(IDictionary<string, IList<string>> dict)
4747
public string Protocol => GetArgumentOrDefault("protocol");
4848
public string Host => GetArgumentOrDefault("host");
4949
public string Path => GetArgumentOrDefault("path");
50-
public string UserName => GetArgumentOrDefault("username");
51-
public string Password => GetArgumentOrDefault("password");
50+
51+
public string AuthType => GetArgumentOrDefault(Constants.CredentialProtocol.AuthTypeKey);
52+
public string Credential => GetArgumentOrDefault(Constants.CredentialProtocol.CredentialKey);
53+
public string UserName => GetArgumentOrDefault(Constants.CredentialProtocol.UserNameKey);
54+
public string Password => GetArgumentOrDefault(Constants.CredentialProtocol.PasswordKey);
55+
public bool IsEphemeral => StringExtensions.IsTruthy(GetArgumentOrDefault(Constants.CredentialProtocol.EphemeralKey));
56+
5257
public IList<string> WwwAuth => GetMultiArgumentOrDefault("wwwauth");
5358

5459
/// <summary>

‎src/Core/GitResponse.cs‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public class GitResponse
4343
private readonly Dictionary<string, string> _state = new(StringComparer.Ordinal);
4444
private ReadOnlyDictionary<string, string> _stateView;
4545

46-
private GitResponse(ICredential credential, bool isContinue, bool isCancelled, bool isYielded)
46+
private GitResponse(ICredential credential, bool isEphemeral = false, string authType = null, bool isContinue = false, bool isCancelled = false, bool isYielded = false)
4747
{
4848
// At most one of Continue, Cancel, Yield may be set (Ok is "none of them").
4949
if ((isContinue && isCancelled) ||
@@ -71,6 +71,9 @@ private GitResponse(ICredential credential, bool isContinue, bool isCancelled, b
7171
}
7272

7373
Credential = credential;
74+
IsCredentialEphemeral = isEphemeral;
75+
AuthType = authType;
76+
7477
IsContinue = isContinue;
7578
IsCancelled = isCancelled;
7679
IsYielded = isYielded;
@@ -81,15 +84,15 @@ private GitResponse(ICredential credential, bool isContinue, bool isCancelled, b
8184
/// </summary>
8285
/// <remarks>Equivalent to <see cref="Ok(ICredential)"/>.</remarks>
8386
public GitResponse(ICredential credential)
84-
: this(credential, isContinue: false, isCancelled: false, isYielded: false)
87+
: this(credential, authType: null)
8588
{
8689
}
8790

8891
/// <summary>
8992
/// Construct a successful response carrying the given credential.
9093
/// </summary>
91-
public static GitResponse Ok(ICredential credential) =>
92-
new GitResponse(credential, isContinue: false, isCancelled: false, isYielded: false);
94+
public static GitResponse Ok(ICredential credential, bool isEphemeral = false, string authtype = null) =>
95+
new(credential, isEphemeral: isEphemeral, authType: authtype);
9396

9497
/// <summary>
9598
/// Construct a successful response carrying the given credential and
@@ -101,8 +104,8 @@ public static GitResponse Ok(ICredential credential) =>
101104
/// multistage HTTP authentication (NTLM/Kerberos) and any flow where the
102105
/// helper wants to be invoked again after the next server response.
103106
/// </remarks>
104-
public static GitResponse Continue(ICredential credential) =>
105-
new GitResponse(credential, isContinue: true, isCancelled: false, isYielded: false);
107+
public static GitResponse Continue(ICredential credential, bool isEphemeral = false, string authType = null) =>
108+
new (credential, isEphemeral: isEphemeral, authType: authType, isContinue: true);
106109

107110
/// <summary>
108111
/// Construct a cancellation response: the provider declined to produce a
@@ -117,7 +120,7 @@ public static GitResponse Continue(ICredential credential) =>
117120
/// cancelled response are ignored.
118121
/// </remarks>
119122
public static GitResponse Cancel() =>
120-
new GitResponse(credential: null, isContinue: false, isCancelled: true, isYielded: false);
123+
new GitResponse(credential: null, isCancelled: true);
121124

122125
/// <summary>
123126
/// Construct a yielded response: the provider has nothing to contribute
@@ -132,14 +135,24 @@ public static GitResponse Cancel() =>
132135
/// set on a yielded response are ignored.
133136
/// </remarks>
134137
public static GitResponse Yield() =>
135-
new GitResponse(credential: null, isContinue: false, isCancelled: false, isYielded: true);
138+
new GitResponse(credential: null, isYielded: true);
136139

137140
/// <summary>
138141
/// The credential resolved or generated for the request, or <see langword="null"/>
139142
/// when <see cref="IsCancelled"/> or <see cref="IsYielded"/> is <see langword="true"/>.
140143
/// </summary>
141144
public ICredential Credential { get; }
142145

146+
/// <summary>
147+
/// The credential is ephemeral (or generated) and not to be stored on success.
148+
/// </summary>
149+
public bool IsCredentialEphemeral { get; }
150+
151+
/// <summary>
152+
/// The special Autorization type for the supplied credential.
153+
/// </summary>
154+
public string AuthType { get; }
155+
143156
/// <summary>
144157
/// <see langword="true"/> when the provider expects a further round of
145158
/// authentication. The command layer translates this into a <c>continue=1</c>

0 commit comments

Comments
 (0)