Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

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

The helper reaches its invocation's session over a channel that only the same
Expand Down
23 changes: 21 additions & 2 deletions rust/crates/git-host/src/authentication.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@ pub struct Session {
token: Zeroizing<String>,
pending: Vec<Pending>,
attempts: HashMap<String, usize>,
/// A prompt ended without an answer from the host (see [`Session::unanswered`]).
unanswered: bool,
helper: PathBuf,
sink: FailureSink,
}
Expand All @@ -152,6 +154,7 @@ impl Session {
token: Zeroizing::new(random_hex::<32>()?),
pending: Vec::new(),
attempts: HashMap::new(),
unanswered: false,
helper: std::env::current_exe()?,
sink: failure_log::emit,
})
Expand Down Expand Up @@ -194,19 +197,29 @@ impl Session {
let mut context = Context {
token: self.token.as_bytes(),
attempts: &mut self.attempts,
unanswered: &mut self.unanswered,
sink: self.sink,
challenges: Vec::new(),
};
self.pending
.retain_mut(|pending| pending.advance(&mut context, now));
Ok(context.challenges)
}

/// Whether a prompt of this session ended without an answer from the
/// host: the user cancelled it, or it expired while the host showed it.
/// The helper then failed, so offering a retry would only ask the same
/// user again. A helper that left by itself does not count.
pub fn unanswered(&self) -> bool {
self.unanswered
}
}

/// Session state that every connection consults.
struct Context<'a> {
token: &'a [u8],
attempts: &'a mut HashMap<String, usize>,
unanswered: &'a mut bool,
sink: FailureSink,
challenges: Vec<Challenge>,
}
Expand Down Expand Up @@ -283,7 +296,10 @@ impl Pending {
return false;
}
// The user did not answer before the prompt timeout.
Stage::Answer { .. } => "wait_answer",
Stage::Answer { .. } => {
*context.unanswered = true;
"wait_answer"
}
Stage::Reply { .. } => "write_response",
// The helper stayed connected after reading its answer.
Stage::Drain => "drain_helper",
Expand All @@ -303,7 +319,10 @@ impl Pending {
self.advance(context, now)
}
// log-exempt: User cancellation: the host cancelled the prompt; the helper sees the channel close and fails.
Ok(None) | Err(mpsc::TryRecvError::Disconnected) => false,
Ok(None) | Err(mpsc::TryRecvError::Disconnected) => {
*context.unanswered = true;
false
}
Err(mpsc::TryRecvError::Empty) => self.helper_waiting(context.sink),
},
Stage::Reply { frame, written } => match deliver(&mut self.stream, frame, written) {
Expand Down
6 changes: 6 additions & 0 deletions rust/crates/git-host/src/authentication/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@ fn answer_reaches_the_helper_exactly_once() {
assert!(!respond(&id, Some("replayed".into())));
let answer = finish(&mut fixture.session, helper).unwrap();
assert_eq!(answer, format!("{CREDENTIAL}\n").into_bytes());
assert!(!fixture.session.unanswered());
assert!(recorded().is_empty());
}

Expand All @@ -225,10 +226,12 @@ fn cancelled_prompt_fails_the_helper() {
let mut fixture = fixture();
let helper = spawn_ask(&fixture.address, &fixture.token, "Password:");
let challenge = next_challenge(&mut fixture.session);
assert!(!fixture.session.unanswered());
assert!(respond(&challenge.request_id, None));
let error = finish(&mut fixture.session, helper).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof);
assert!(!registry().contains_key(&challenge.request_id));
assert!(fixture.session.unanswered());
assert!(recorded().is_empty());
}

Expand Down Expand Up @@ -356,6 +359,8 @@ fn helper_that_leaves_ends_its_prompt() {
}
assert!(!respond(&challenge.request_id, Some(CREDENTIAL.into())));
assert!(fixture.session.pending.is_empty());
// The helper gave up by itself; the user never declined anything.
assert!(!fixture.session.unanswered());
assert!(recorded().is_empty());
}

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

Expand Down
62 changes: 51 additions & 11 deletions rust/crates/git/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,16 +189,16 @@ pub(crate) fn execute_git_with_environment(
) -> Result<GitCommandResponse, CoreError> {
let arguments = execution_policy::arguments(arguments);
let mut retry_scope = None;
for attempt in 0..3 {
let output = capture_git_process(
for round in 0..3 {
let attempt = capture_git_attempt(
root,
&arguments,
input.clone(),
disable_optional_locks,
environment,
true,
)?;
let response = output.into_command_response(&arguments);
let response = attempt.output.into_command_response(&arguments);
record_git_invocation(&response);
let authentication_failed = [
"Authentication failed",
Expand All @@ -214,11 +214,14 @@ pub(crate) fn execute_git_with_environment(
"fetch" | "pull" | "push" | "clone"
)
});
// A user who cancelled or let a prompt expire has already declined;
// asking whether to retry would only repeat the question.
if response.exit_code == 0
|| !authentication_failed
|| !transfer
|| !execution_policy::current().interactive
|| attempt == 2
|| attempt.prompt_unanswered
|| round == 2
{
return Ok(response);
}
Expand All @@ -233,7 +236,7 @@ pub(crate) fn execute_git_with_environment(
execution_events::emit(
serde_json::json!({ "type": "authentication", "requestId": confirmation.request_id,
"prompt": "Git authentication failed. Retry with credentials entered in Lithe, bypassing the credential helper for this retry?",
"secret": false, "retry": true, "attempt": attempt + 2, "workingDirectory": root }),
"secret": false, "retry": true, "attempt": round + 2, "workingDirectory": root }),
);
let retry = confirmation
.wait(|| lithe_protocol::cancellation::check().is_err())
Expand Down Expand Up @@ -284,6 +287,34 @@ pub(crate) fn capture_git_process(
environment: &[(String, String)],
visible: bool,
) -> Result<GitProcessOutput, CoreError> {
capture_git_attempt(
root,
arguments,
input,
disable_optional_locks,
environment,
visible,
)
.map(|attempt| attempt.output)
}

/// One Git process and what became of the credential prompts it asked.
struct GitAttempt {
output: GitProcessOutput,
/// A prompt ended without an answer from the user: they cancelled it, or
/// it expired. The authentication failure that follows is their decision,
/// so it is not offered for retry.
prompt_unanswered: bool,
}

fn capture_git_attempt(
root: &str,
arguments: &[String],
input: Option<String>,
disable_optional_locks: bool,
environment: &[(String, String)],
visible: bool,
) -> Result<GitAttempt, CoreError> {
validate_windows_git_path(Path::new(root)).map_err(git_path_error)?;
lithe_protocol::cancellation::check()?;
// Refuse before the trace: in safe mode no Git starts, so there is nothing to record.
Expand All @@ -299,7 +330,11 @@ pub(crate) fn capture_git_process(
visible,
&mut trace,
) {
Some(result) => result,
// Remote Git never asks through this host's AskPass channel.
Some(result) => result.map(|output| GitAttempt {
output,
prompt_unanswered: false,
}),
None => capture_local_git_process(
root,
arguments,
Expand All @@ -322,7 +357,7 @@ fn capture_local_git_process(
environment: &[(String, String)],
visible: bool,
trace: &mut command_trace::Trace,
) -> Result<GitProcessOutput, CoreError> {
) -> Result<GitAttempt, CoreError> {
let mut process = git_process()?;
let version = lithe_git_host::configuration::version(process.get_program(), || {
lithe_protocol::cancellation::check().is_err()
Expand Down Expand Up @@ -460,10 +495,15 @@ fn capture_local_git_process(
if let Some(error) = error {
return Err(error);
}
Ok(GitProcessOutput {
stdout: output.stdout,
stderr: output.stderr,
exit_code: exit_code.unwrap_or(1),
Ok(GitAttempt {
output: GitProcessOutput {
stdout: output.stdout,
stderr: output.stderr,
exit_code: exit_code.unwrap_or(1),
},
prompt_unanswered: authentication
.as_ref()
.is_some_and(lithe_git_host::authentication::Session::unanswered),
})
}

Expand Down
Loading