Skip to content

Commit 94408ca

Browse files
authored
fix(git): 用户取消或放过凭据询问后不再询问是否重试(#2231) (#142)
AskPass 会话记录本次 Git 进程是否有询问没得到回答(用户取消,或询问超过 180 秒过期)。认证失败后的重试循环看到这个标记就直接返回失败,不再弹出“是否在 Lithe 中重新输入”的询问:用户已经拒绝回答,再问一次只会重复同一个问题。回答了但认证仍被拒的情况照旧询问是否重试;助手自己退出、远程 Git 不算未回答。
1 parent 4ab420e commit 94408ca

4 files changed

Lines changed: 85 additions & 17 deletions

File tree

‎rust/contracts/rust-core-api.md‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1267,10 +1267,13 @@ setting is editable through this command.
12671267
`git.authRespond` takes `{ requestId: string, answer: string | null }` and returns
12681268
`{ accepted: boolean }`. Opaque IDs are invocation-owned, unguessable and single
12691269
use; stale or invalid answers return false. Answers are bounded to 8 KiB without
1270-
NUL/newlines. Null cancels the challenge. Hosts also cancel its owning operation
1271-
when the user cancels the dialog. An event with `retry: true` requires the exact
1272-
answer `"retry"` to repeat the failed transfer with helper bypass, at most three
1273-
total attempts. The AskPass C ABI is called only in the child app's early helper
1270+
NUL/newlines. Null cancels the challenge: the helper fails, Git ends with its
1271+
authentication failure, and Core returns that failure without asking whether to
1272+
retry, as it does when a challenge expires unanswered. Hosts therefore need not
1273+
cancel the owning operation when the user dismisses the dialog. An event with
1274+
`retry: true` follows only a failed attempt in which no challenge was cancelled
1275+
or expired; it requires the exact answer `"retry"` to repeat the failed transfer
1276+
with helper bypass, at most three total attempts. The AskPass C ABI is called only in the child app's early helper
12741277
mode. Credential answers are never copied into events or settings.
12751278

12761279
The helper reaches its invocation's session over a channel that only the same

‎rust/crates/git-host/src/authentication.rs‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,8 @@ pub struct Session {
140140
token: Zeroizing<String>,
141141
pending: Vec<Pending>,
142142
attempts: HashMap<String, usize>,
143+
/// A prompt ended without an answer from the host (see [`Session::unanswered`]).
144+
unanswered: bool,
143145
helper: PathBuf,
144146
sink: FailureSink,
145147
}
@@ -152,6 +154,7 @@ impl Session {
152154
token: Zeroizing::new(random_hex::<32>()?),
153155
pending: Vec::new(),
154156
attempts: HashMap::new(),
157+
unanswered: false,
155158
helper: std::env::current_exe()?,
156159
sink: failure_log::emit,
157160
})
@@ -194,19 +197,29 @@ impl Session {
194197
let mut context = Context {
195198
token: self.token.as_bytes(),
196199
attempts: &mut self.attempts,
200+
unanswered: &mut self.unanswered,
197201
sink: self.sink,
198202
challenges: Vec::new(),
199203
};
200204
self.pending
201205
.retain_mut(|pending| pending.advance(&mut context, now));
202206
Ok(context.challenges)
203207
}
208+
209+
/// Whether a prompt of this session ended without an answer from the
210+
/// host: the user cancelled it, or it expired while the host showed it.
211+
/// The helper then failed, so offering a retry would only ask the same
212+
/// user again. A helper that left by itself does not count.
213+
pub fn unanswered(&self) -> bool {
214+
self.unanswered
215+
}
204216
}
205217

206218
/// Session state that every connection consults.
207219
struct Context<'a> {
208220
token: &'a [u8],
209221
attempts: &'a mut HashMap<String, usize>,
222+
unanswered: &'a mut bool,
210223
sink: FailureSink,
211224
challenges: Vec<Challenge>,
212225
}
@@ -283,7 +296,10 @@ impl Pending {
283296
return false;
284297
}
285298
// The user did not answer before the prompt timeout.
286-
Stage::Answer { .. } => "wait_answer",
299+
Stage::Answer { .. } => {
300+
*context.unanswered = true;
301+
"wait_answer"
302+
}
287303
Stage::Reply { .. } => "write_response",
288304
// The helper stayed connected after reading its answer.
289305
Stage::Drain => "drain_helper",
@@ -303,7 +319,10 @@ impl Pending {
303319
self.advance(context, now)
304320
}
305321
// log-exempt: User cancellation: the host cancelled the prompt; the helper sees the channel close and fails.
306-
Ok(None) | Err(mpsc::TryRecvError::Disconnected) => false,
322+
Ok(None) | Err(mpsc::TryRecvError::Disconnected) => {
323+
*context.unanswered = true;
324+
false
325+
}
307326
Err(mpsc::TryRecvError::Empty) => self.helper_waiting(context.sink),
308327
},
309328
Stage::Reply { frame, written } => match deliver(&mut self.stream, frame, written) {

‎rust/crates/git-host/src/authentication/tests.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,7 @@ fn answer_reaches_the_helper_exactly_once() {
205205
assert!(!respond(&id, Some("replayed".into())));
206206
let answer = finish(&mut fixture.session, helper).unwrap();
207207
assert_eq!(answer, format!("{CREDENTIAL}\n").into_bytes());
208+
assert!(!fixture.session.unanswered());
208209
assert!(recorded().is_empty());
209210
}
210211

@@ -225,10 +226,12 @@ fn cancelled_prompt_fails_the_helper() {
225226
let mut fixture = fixture();
226227
let helper = spawn_ask(&fixture.address, &fixture.token, "Password:");
227228
let challenge = next_challenge(&mut fixture.session);
229+
assert!(!fixture.session.unanswered());
228230
assert!(respond(&challenge.request_id, None));
229231
let error = finish(&mut fixture.session, helper).unwrap_err();
230232
assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof);
231233
assert!(!registry().contains_key(&challenge.request_id));
234+
assert!(fixture.session.unanswered());
232235
assert!(recorded().is_empty());
233236
}
234237

@@ -356,6 +359,8 @@ fn helper_that_leaves_ends_its_prompt() {
356359
}
357360
assert!(!respond(&challenge.request_id, Some(CREDENTIAL.into())));
358361
assert!(fixture.session.pending.is_empty());
362+
// The helper gave up by itself; the user never declined anything.
363+
assert!(!fixture.session.unanswered());
359364
assert!(recorded().is_empty());
360365
}
361366

@@ -410,6 +415,7 @@ fn unanswered_prompt_is_recorded_at_its_deadline() {
410415
assert!(fixture.session.pending.is_empty());
411416
assert_no_answer(join(helper));
412417
assert!(!respond(&challenge.request_id, Some(CREDENTIAL.into())));
418+
assert!(fixture.session.unanswered());
413419
assert_eq!(recorded(), [failure("wait_answer", "TimedOut")]);
414420
}
415421

‎rust/crates/git/src/process.rs‎

Lines changed: 51 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -189,16 +189,16 @@ pub(crate) fn execute_git_with_environment(
189189
) -> Result<GitCommandResponse, CoreError> {
190190
let arguments = execution_policy::arguments(arguments);
191191
let mut retry_scope = None;
192-
for attempt in 0..3 {
193-
let output = capture_git_process(
192+
for round in 0..3 {
193+
let attempt = capture_git_attempt(
194194
root,
195195
&arguments,
196196
input.clone(),
197197
disable_optional_locks,
198198
environment,
199199
true,
200200
)?;
201-
let response = output.into_command_response(&arguments);
201+
let response = attempt.output.into_command_response(&arguments);
202202
record_git_invocation(&response);
203203
let authentication_failed = [
204204
"Authentication failed",
@@ -214,11 +214,14 @@ pub(crate) fn execute_git_with_environment(
214214
"fetch" | "pull" | "push" | "clone"
215215
)
216216
});
217+
// A user who cancelled or let a prompt expire has already declined;
218+
// asking whether to retry would only repeat the question.
217219
if response.exit_code == 0
218220
|| !authentication_failed
219221
|| !transfer
220222
|| !execution_policy::current().interactive
221-
|| attempt == 2
223+
|| attempt.prompt_unanswered
224+
|| round == 2
222225
{
223226
return Ok(response);
224227
}
@@ -233,7 +236,7 @@ pub(crate) fn execute_git_with_environment(
233236
execution_events::emit(
234237
serde_json::json!({ "type": "authentication", "requestId": confirmation.request_id,
235238
"prompt": "Git authentication failed. Retry with credentials entered in Lithe, bypassing the credential helper for this retry?",
236-
"secret": false, "retry": true, "attempt": attempt + 2, "workingDirectory": root }),
239+
"secret": false, "retry": true, "attempt": round + 2, "workingDirectory": root }),
237240
);
238241
let retry = confirmation
239242
.wait(|| lithe_protocol::cancellation::check().is_err())
@@ -284,6 +287,34 @@ pub(crate) fn capture_git_process(
284287
environment: &[(String, String)],
285288
visible: bool,
286289
) -> Result<GitProcessOutput, CoreError> {
290+
capture_git_attempt(
291+
root,
292+
arguments,
293+
input,
294+
disable_optional_locks,
295+
environment,
296+
visible,
297+
)
298+
.map(|attempt| attempt.output)
299+
}
300+
301+
/// One Git process and what became of the credential prompts it asked.
302+
struct GitAttempt {
303+
output: GitProcessOutput,
304+
/// A prompt ended without an answer from the user: they cancelled it, or
305+
/// it expired. The authentication failure that follows is their decision,
306+
/// so it is not offered for retry.
307+
prompt_unanswered: bool,
308+
}
309+
310+
fn capture_git_attempt(
311+
root: &str,
312+
arguments: &[String],
313+
input: Option<String>,
314+
disable_optional_locks: bool,
315+
environment: &[(String, String)],
316+
visible: bool,
317+
) -> Result<GitAttempt, CoreError> {
287318
validate_windows_git_path(Path::new(root)).map_err(git_path_error)?;
288319
lithe_protocol::cancellation::check()?;
289320
// Refuse before the trace: in safe mode no Git starts, so there is nothing to record.
@@ -299,7 +330,11 @@ pub(crate) fn capture_git_process(
299330
visible,
300331
&mut trace,
301332
) {
302-
Some(result) => result,
333+
// Remote Git never asks through this host's AskPass channel.
334+
Some(result) => result.map(|output| GitAttempt {
335+
output,
336+
prompt_unanswered: false,
337+
}),
303338
None => capture_local_git_process(
304339
root,
305340
arguments,
@@ -322,7 +357,7 @@ fn capture_local_git_process(
322357
environment: &[(String, String)],
323358
visible: bool,
324359
trace: &mut command_trace::Trace,
325-
) -> Result<GitProcessOutput, CoreError> {
360+
) -> Result<GitAttempt, CoreError> {
326361
let mut process = git_process()?;
327362
let version = lithe_git_host::configuration::version(process.get_program(), || {
328363
lithe_protocol::cancellation::check().is_err()
@@ -460,10 +495,15 @@ fn capture_local_git_process(
460495
if let Some(error) = error {
461496
return Err(error);
462497
}
463-
Ok(GitProcessOutput {
464-
stdout: output.stdout,
465-
stderr: output.stderr,
466-
exit_code: exit_code.unwrap_or(1),
498+
Ok(GitAttempt {
499+
output: GitProcessOutput {
500+
stdout: output.stdout,
501+
stderr: output.stderr,
502+
exit_code: exit_code.unwrap_or(1),
503+
},
504+
prompt_unanswered: authentication
505+
.as_ref()
506+
.is_some_and(lithe_git_host::authentication::Session::unanswered),
467507
})
468508
}
469509

0 commit comments

Comments
 (0)