credential/wincred: erase matching creds only

The credential erase request typically includes protocol, host, username and password. credential-wincred erases stored credentials that match protocol, host and username, regardless of password. This is confusing in the case the stored password differs from that in the request. This case can occur when multiple credential helpers are configured. Only erase credential if stored password matches request (or request omits password). This fixes test "helper (wincred) does not erase a password distinct from input" when t0303 is run with GIT_TEST_CREDENTIAL_HELPER set to "wincred". This test was added in aeb21ce22e (credential: avoid erasing distinct password, 2023-06-13). Signed-off-by: M Hickford <mirth.hickford@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

M Hickford committed Jul 26, 2023 at 19:51 UTC cb626f8e5cb76ce081ab0a02656611f05a54cfb5
1 file changed +16 -4
contrib/credential/wincred/git-credential-wincred.c
+16 -4
@@ -109,7 +109,18 @@ static int match_part_last(LPCWSTR *ptarget, LPCWSTR want, LPCWSTR delim)
109 return match_part_with_last(ptarget, want, delim, 1);
110 }
111
112 -static int match_cred(const CREDENTIALW *cred)
112 +static int match_cred_password(const CREDENTIALW *cred) {
113 + int ret;
114 + WCHAR *cred_password = xmalloc(cred->CredentialBlobSize);
115 + wcsncpy_s(cred_password, cred->CredentialBlobSize,
116 + (LPCWSTR)cred->CredentialBlob,
117 + cred->CredentialBlobSize / sizeof(WCHAR));
118 + ret = !wcscmp(cred_password, password);
119 + free(cred_password);
120 + return ret;
121 +}
122 +
123 +static int match_cred(const CREDENTIALW *cred, int match_password)
124 {
125 LPCWSTR target = cred->TargetName;
126 if (wusername && wcscmp(wusername, cred->UserName ? cred->UserName : L""))
@@ -119,7 +130,8 @@ static int match_cred(const CREDENTIALW *cred)
130 match_part(&target, protocol, L"://") &&
131 match_part_last(&target, wusername, L"@") &&
132 match_part(&target, host, L"/") &&
122 - match_part(&target, path, L"");
133 + match_part(&target, path, L"") &&
134 + (!match_password || match_cred_password(cred));
135 }
136
137 static void get_credential(void)
@@ -134,7 +146,7 @@ static void get_credential(void)
146
147 /* search for the first credential that matches username */
148 for (i = 0; i < num_creds; ++i)
137 - if (match_cred(creds[i])) {
149 + if (match_cred(creds[i], 0)) {
150 write_item("username", creds[i]->UserName,
151 creds[i]->UserName ? wcslen(creds[i]->UserName) : 0);
152 write_item("password",
@@ -196,7 +208,7 @@ static void erase_credential(void)
208 return;
209
210 for (i = 0; i < num_creds; ++i) {
199 - if (match_cred(creds[i]))
211 + if (match_cred(creds[i], password != NULL))
212 CredDeleteW(creds[i]->TargetName, creds[i]->Type, 0);
213 }
214