diff --git a/desktop/cmd/lithe/main.go b/desktop/cmd/lithe/main.go index e6b7d646e..6db18e868 100644 --- a/desktop/cmd/lithe/main.go +++ b/desktop/cmd/lithe/main.go @@ -22,6 +22,12 @@ import ( ) func main() { + // Git and SSH run this program as the AskPass helper of a Git command the user started in + // Lithe. The helper only relays one question to that window and prints the answer, so it + // returns before any window, log, store or login environment exists. + if prompt, helper := core.GitAskPassRequest(os.Args); helper { + os.Exit(core.GitAskPass(prompt)) + } // AppKit needs the process's main thread for the application and its windows. Pin the // main goroutine before any setup that can yield, so the scheduler cannot move it. runtime.LockOSThread() diff --git a/desktop/internal/core/bridge.go b/desktop/internal/core/bridge.go index 59ae3a502..d01f22b96 100644 --- a/desktop/internal/core/bridge.go +++ b/desktop/internal/core/bridge.go @@ -13,6 +13,17 @@ import ( "unsafe" ) +// GitAskPass runs this process as the AskPass helper GitAskPassRequest detected: Core sends +// prompt to the Lithe request that started Git, waits for the user's answer, prints it on +// standard output for Git or SSH and returns the exit status, 0 when it printed an answer and 1 +// when there is none (cancelled, expired or refused). Call it first in main and exit with its +// result: a helper process opens no window, log or store. +func GitAskPass(prompt string) int { + cPrompt := C.CString(prompt) + defer C.free(unsafe.Pointer(cPrompt)) + return int(C.lithe_core_git_askpass(cPrompt)) +} + // classifyTextBytes borrows the Go byte slice only for the synchronous Core // call. The slice contains no pointers, and Core neither retains nor mutates it. func classifyTextBytes(data []byte) int { diff --git a/desktop/internal/core/client.go b/desktop/internal/core/client.go index ca191efe4..c40e2d3b2 100644 --- a/desktop/internal/core/client.go +++ b/desktop/internal/core/client.go @@ -53,6 +53,10 @@ type gitExecution struct { // (WithProjectCodeAllowed): Core starts no Git process for it and answers // CodeGitUntrustedWorkspace. Nil keeps Core's default, which allows Git. ProjectCodeAllowed *bool `json:"projectCodeAllowed,omitempty"` + // Interactive lets the Git processes the user sees ask for credentials through Lithe + // (WithGitAuthentication). Core then requires the request to observe execution events, + // which carry the questions. + Interactive bool `json:"interactive,omitempty"` } // responseEnvelope is the response the kernel encodes (CoreResponse in the Rust protocol). @@ -110,11 +114,12 @@ func (c *Client) execute(ctx context.Context, command string, payload, result an payload = struct{}{} } operationID := fmt.Sprintf("desktop-%d", nextCoreOperation.Add(1)) + execution := gitExecutionOf(ctx, command) request, err := json.Marshal(requestEnvelope{ OperationID: operationID, Command: command, Payload: payload, - GitExecution: gitExecutionOf(ctx, command), + GitExecution: execution, Origin: requestOriginOf(ctx), }) if err != nil { @@ -132,6 +137,14 @@ func (c *Client) execute(ctx context.Context, command string, payload, result an } // A Git request of a context with a console is observed so its commands are recorded. observer = gitConsoleObserver(ctx, command, request, observer) + if execution != nil && execution.Interactive { + // The questions of an interactive request arrive as its events, and Core refuses one + // that observes none. Closing returned tells each open question that no answer reaches + // its request any more. + returned := make(chan struct{}) + defer close(returned) + observer = gitAuthenticationObserver(gitAuthenticationOf(ctx, command), returned, observer) + } if observer == nil { return nil, decodeResponse(ctx, command, call(ctx, operationID, request), result) } diff --git a/desktop/internal/core/gitauth.go b/desktop/internal/core/gitauth.go new file mode 100644 index 000000000..f6f543a53 --- /dev/null +++ b/desktop/internal/core/gitauth.go @@ -0,0 +1,135 @@ +package core + +import ( + "bytes" + "context" + "encoding/json" + "os" + "strings" +) + +// Git authentication: Core lets a Git process the user started call this program as its +// AskPass helper (GIT_ASKPASS, SSH_ASKPASS). The helper process forwards the question over a +// channel only this account can reach to the request that started Git, which reports it as an +// execution event; the host asks the user and answers with git.authRespond. Core redacts the +// question, keeps the answer out of logs and zeroes its copies once Git has read it. + +// GitAuthChallenge is a question a running Git request asks: a user name, a password, token or +// passphrase (Secret), or, after a transfer failed to authenticate, whether to retry it once +// with credentials typed in Lithe instead of the credential helper (Retry). +type GitAuthChallenge struct { + // RequestID names the challenge to GitAuthRespond. + RequestID string + // Prompt is Git's or SSH's own question with Core's redactions applied. It is upstream text, + // shown as it is. A Retry challenge carries Core's English wording, which the host replaces + // with its own translated question. + Prompt string + // Secret says the answer must not be shown or kept. + Secret bool + // Retry is the question whether to retry the transfer; only GitRetryAnswer accepts it. + Retry bool + // Attempt counts, from 1, how often the Git process asked the same question. A Retry + // challenge carries the number of the transfer a retry would start instead, from 2. + Attempt int + // WorkingDirectory is the directory the Git process runs in. + WorkingDirectory string + // Done is closed once the request that asked has returned; no answer reaches it after that. + Done <-chan struct{} +} + +// GitRetryAnswer is the answer to a Retry challenge that retries the transfer. +const GitRetryAnswer = "retry" + +type gitAuthenticationKey struct{} + +// WithGitAuthentication returns a context whose Git requests may ask the user for credentials: +// Core lets the Git processes the user sees (not a request's internal queries) use this program +// as their AskPass helper, and each question reaches prompt. prompt runs on the request's +// goroutine and must return promptly, posting the question to the UI thread; the Git process +// waits for GitAuthRespond, for at most Core's prompt deadline, and fails authentication +// without an answer. Give it only to operations the user started: an automatic refresh must +// fail instead of asking. +func WithGitAuthentication(ctx context.Context, prompt func(GitAuthChallenge)) context.Context { + return context.WithValue(ctx, gitAuthenticationKey{}, prompt) +} + +// gitAuthenticationOf is the prompt of a request of command, nil when ctx has none or command +// starts no Git process. +func gitAuthenticationOf(ctx context.Context, command string) func(GitAuthChallenge) { + if !strings.HasPrefix(command, "git.") || gitConsoleUnrecorded[command] { + return nil + } + prompt, _ := ctx.Value(gitAuthenticationKey{}).(func(GitAuthChallenge)) + return prompt +} + +// gitAuthenticationEvent is the execution event of a question Git asked. +var gitAuthenticationEvent = []byte(`"authentication"`) + +// gitAuthenticationObserver hands each authentication event of a request to prompt, with done +// closed when the request returns, and passes every event on to next. +func gitAuthenticationObserver(prompt func(GitAuthChallenge), done <-chan struct{}, next func(json.RawMessage)) func(json.RawMessage) { + return func(raw json.RawMessage) { + // Git prints many output lines and asks rarely; only a line naming the kind is decoded. + if bytes.Contains(raw, gitAuthenticationEvent) { + var event struct { + Type string `json:"type"` + RequestID string `json:"requestId"` + Prompt string `json:"prompt"` + Secret bool `json:"secret"` + Retry bool `json:"retry"` + Attempt int `json:"attempt"` + WorkingDirectory string `json:"workingDirectory"` + } + if json.Unmarshal(raw, &event) == nil && event.Type == "authentication" && event.RequestID != "" { + prompt(GitAuthChallenge{ + RequestID: event.RequestID, + Prompt: event.Prompt, + Secret: event.Secret, + Retry: event.Retry, + Attempt: event.Attempt, + WorkingDirectory: event.WorkingDirectory, + Done: done, + }) + } + } + if next != nil { + next(raw) + } + } +} + +// gitAuthReply is the payload of git.authRespond. A nil Answer cancels the question. +type gitAuthReply struct { + RequestID string `json:"requestId"` + Answer *string `json:"answer"` +} + +// GitAuthRespond answers the challenge requestID with the text the user typed, GitRetryAnswer to +// retry, or nil to cancel. accepted is false when the challenge no longer waits: it was already +// answered, it expired, its request returned, or Core refused the answer (longer than 8192 bytes, +// or containing NUL, CR or LF). The answer is never logged. Core answers at once, so the call +// may run on any goroutine, but not on the UI thread. +func (c *Client) GitAuthRespond(ctx context.Context, requestID string, answer *string) (accepted bool, err error) { + var result struct { + Accepted bool `json:"accepted"` + } + err = c.Execute(ctx, "git.authRespond", gitAuthReply{RequestID: requestID, Answer: answer}, &result) + return result.Accepted, err +} + +// gitAskPassModeVariable is set by Core in the environment of the helper it names to Git. +const gitAskPassModeVariable = "LITHE_GIT_ASKPASS_MODE" + +// GitAskPassRequest reports whether this process was started as the AskPass helper of an +// interactive Git process, and the question Git or SSH passed as its first argument. args is +// os.Args. +func GitAskPassRequest(args []string) (prompt string, helper bool) { + if os.Getenv(gitAskPassModeVariable) != "1" { + return "", false + } + if len(args) > 1 { + prompt = args[1] + } + return prompt, true +} diff --git a/desktop/internal/core/gitauth_test.go b/desktop/internal/core/gitauth_test.go new file mode 100644 index 000000000..201385727 --- /dev/null +++ b/desktop/internal/core/gitauth_test.go @@ -0,0 +1,256 @@ +package core + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "slices" + "strings" + "sync" + "testing" +) + +// TestMain lets this test binary serve as the AskPass helper Core names to the interactive Git +// processes the tests start: such a run relays its one question and exits instead of running the +// tests, as the Lithe executable does in main. +func TestMain(m *testing.M) { + if prompt, helper := GitAskPassRequest(os.Args); helper { + os.Exit(GitAskPass(prompt)) + } + os.Exit(m.Run()) +} + +// authenticationRemote is a Git HTTP remote that refuses every request with a Basic challenge +// and records the credentials each request carried. +type authenticationRemote struct { + url string + mu sync.Mutex + credentials []string +} + +func newAuthenticationRemote(t *testing.T) *authenticationRemote { + t.Helper() + remote := &authenticationRemote{} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if user, password, ok := r.BasicAuth(); ok { + remote.mu.Lock() + remote.credentials = append(remote.credentials, user+":"+password) + remote.mu.Unlock() + } + w.Header().Set("WWW-Authenticate", `Basic realm="lithe-test"`) + http.Error(w, "authentication required", http.StatusUnauthorized) + })) + t.Cleanup(server.Close) + // A proxy of the host must not stand between Git and the local server. + t.Setenv("no_proxy", "*") + t.Setenv("NO_PROXY", "*") + remote.url = server.URL + "/repository.git" + return remote +} + +func (r *authenticationRemote) received() []string { + r.mu.Lock() + defer r.mu.Unlock() + return slices.Clone(r.credentials) +} + +// repositoryOf creates a repository whose origin is remote. +func repositoryOf(t *testing.T, remote *authenticationRemote) string { + t.Helper() + repository := newRepository(t) + runGit(t, repository, "remote", "add", "origin", remote.url) + return repository +} + +// fetchAnswering fetches the origin of repository in ctx, answering each challenge with answer +// off the request's goroutine as the workbench does, and returns the challenges in the order +// they were asked and the fetch's error. Every answer must be accepted. +func fetchAnswering(t *testing.T, ctx context.Context, repository string, answer func(GitAuthChallenge) *string) ([]GitAuthChallenge, error) { + t.Helper() + client := NewClient() + var mu sync.Mutex + var challenges []GitAuthChallenge + var replies sync.WaitGroup + prompt := func(challenge GitAuthChallenge) { + mu.Lock() + challenges = append(challenges, challenge) + mu.Unlock() + replies.Add(1) + go func() { + defer replies.Done() + accepted, err := client.GitAuthRespond(testContext(t), challenge.RequestID, answer(challenge)) + if err != nil || !accepted { + t.Errorf("answer to %q: accepted = %v, err = %v", challenge.Prompt, accepted, err) + } + }() + } + var err error + finishesWithin(t, "interactive fetch", testDeadline, func() { + err = client.GitFetch(WithGitAuthentication(ctx, prompt), repository, nil) + }) + finishesWithin(t, "answers", testDeadline, replies.Wait) + mu.Lock() + defer mu.Unlock() + return slices.Clone(challenges), err +} + +// challengeKind names a challenge for comparisons: what it asks, not its wording. +func challengeKind(challenge GitAuthChallenge) string { + switch { + case challenge.Retry: + return "retry" + case challenge.Secret: + return "secret" + default: + return "user" + } +} + +func answerText(s string) *string { return &s } + +// A fetch the user started asks for the user name and the password through Lithe, sends them to +// the remote, and after the remote refuses them asks whether to retry; a retry asks again, and a +// cancelled retry question ends the fetch with the authentication failure. +func TestGitAuthenticationRelaysQuestionsAndAnswers(t *testing.T) { + requireGit(t) + remote := newAuthenticationRemote(t) + repository := repositoryOf(t, remote) + retries := 0 + challenges, err := fetchAnswering(t, testContext(t), repository, func(challenge GitAuthChallenge) *string { + switch challengeKind(challenge) { + case "user": + return answerText("alice") + case "secret": + return answerText("s3cret") + } + retries++ + if retries == 1 { + return answerText(GitRetryAnswer) + } + return nil + }) + if !IsAuthenticationFailure(err) { + t.Fatalf("fetch error = %v, want the authentication failure", err) + } + var kinds []string + for _, challenge := range challenges { + kinds = append(kinds, challengeKind(challenge)) + } + if want := []string{"user", "secret", "retry", "user", "secret", "retry"}; !slices.Equal(kinds, want) { + t.Fatalf("challenges = %q, want %q", kinds, want) + } + user, secret, retry := challenges[0], challenges[1], challenges[2] + if !strings.Contains(user.Prompt, "Username") || user.Attempt != 1 || user.WorkingDirectory == "" { + t.Fatalf("user question = %+v, want Git's question, attempt 1 and the working directory", user) + } + if !strings.Contains(secret.Prompt, "Password") || strings.Contains(secret.Prompt, "alice") { + t.Fatalf("password question = %q, want Git's question without the user name", secret.Prompt) + } + if retry.Attempt != 2 || challenges[5].Attempt != 3 || retry.Prompt == "" { + t.Fatalf("retry questions = %+v, %+v, want transfers 2 and 3", retry, challenges[5]) + } + if got, want := remote.received(), []string{"alice:s3cret", "alice:s3cret"}; !slices.Equal(got, want) { + t.Fatalf("remote received %q, want %q", got, want) + } + for _, challenge := range challenges { + select { + case <-challenge.Done: + default: + t.Fatalf("challenge %q is still open after its request returned", challenge.Prompt) + } + } + // A dialog answered after the request returned reaches nothing. + accepted, err := NewClient().GitAuthRespond(testContext(t), user.RequestID, answerText("late")) + if err != nil || accepted { + t.Fatalf("late answer: accepted = %v, err = %v, want refused", accepted, err) + } +} + +// Cancelling Git's question fails authentication without sending anything to the remote. +func TestGitAuthenticationCancelledQuestionSendsNothing(t *testing.T) { + requireGit(t) + remote := newAuthenticationRemote(t) + repository := repositoryOf(t, remote) + challenges, err := fetchAnswering(t, testContext(t), repository, func(GitAuthChallenge) *string { return nil }) + if !IsAuthenticationFailure(err) { + t.Fatalf("fetch error = %v, want the authentication failure", err) + } + var kinds []string + for _, challenge := range challenges { + kinds = append(kinds, challengeKind(challenge)) + } + t.Logf("challenges after a cancelled question: %q", kinds) + if len(kinds) == 0 || kinds[0] != "user" { + t.Fatalf("challenges = %q, want Git's user name question first", kinds) + } + if got := remote.received(); len(got) != 0 { + t.Fatalf("remote received %q, want no credentials", got) + } +} + +// An automatic refresh never asks, even in a context that could. +func TestGitAuthenticationAutomaticRefreshNeverAsks(t *testing.T) { + requireGit(t) + remote := newAuthenticationRemote(t) + repository := repositoryOf(t, remote) + challenges, err := fetchAnswering(t, AutomaticRefresh(testContext(t)), repository, func(GitAuthChallenge) *string { return answerText("alice") }) + if !IsAuthenticationFailure(err) { + t.Fatalf("fetch error = %v, want the authentication failure", err) + } + if len(challenges) != 0 || len(remote.received()) != 0 { + t.Fatalf("refresh asked %+v and sent %q, want neither", challenges, remote.received()) + } +} + +// Only Git requests of a context that can ask are interactive, never an automatic refresh, and +// the observer hands only authentication events to the prompt while passing on every event. +func TestGitAuthenticationMarksOnlyRequestsThatCanAsk(t *testing.T) { + prompt := func(GitAuthChallenge) {} + asks := WithGitAuthentication(context.Background(), prompt) + cases := []struct { + name string + ctx context.Context + command string + want string + }{ + {"asks", asks, "git.fetch", `{"interactive":true}`}, + {"refresh", AutomaticRefresh(asks), "git.fetch", `null`}, + {"answer", asks, "git.authRespond", `null`}, + {"never runs Git", asks, "git.consolePresentation", `null`}, + {"not Git", asks, "core.ping", `null`}, + {"cannot ask", context.Background(), "git.fetch", `null`}, + } + for _, c := range cases { + got, err := json.Marshal(gitExecutionOf(c.ctx, c.command)) + if err != nil || string(got) != c.want { + t.Fatalf("%s: gitExecution = %s (%v), want %s", c.name, got, err, c.want) + } + } + + done := make(chan struct{}) + var asked []GitAuthChallenge + var passed []string + observe := gitAuthenticationObserver(func(challenge GitAuthChallenge) { asked = append(asked, challenge) }, done, + func(raw json.RawMessage) { passed = append(passed, string(raw)) }) + events := []string{ + `{"type":"output","line":"authentication"}`, + `{"type":"authentication","requestId":"","prompt":"Username"}`, + `{"type":"authentication","requestId":"r1","prompt":"Password for 'https://example.invalid': ","secret":true,"attempt":1,"workingDirectory":"/repo"}`, + `not json "authentication"`, + } + for _, event := range events { + observe(json.RawMessage(event)) + } + if !slices.Equal(passed, events) { + t.Fatalf("passed on %q, want every event", passed) + } + if len(asked) != 1 { + t.Fatalf("asked %+v, want only the complete authentication event", asked) + } + want := GitAuthChallenge{RequestID: "r1", Prompt: "Password for 'https://example.invalid': ", Secret: true, Attempt: 1, WorkingDirectory: "/repo", Done: done} + if asked[0] != want { + t.Fatalf("challenge = %+v, want %+v", asked[0], want) + } +} diff --git a/desktop/internal/core/gitconsole.go b/desktop/internal/core/gitconsole.go index 15f53052b..7a48ae29b 100644 --- a/desktop/internal/core/gitconsole.go +++ b/desktop/internal/core/gitconsole.go @@ -836,10 +836,12 @@ func WithProjectCodeAllowed(ctx context.Context, allowed func() bool) context.Co // gitExecutionOf is the Git policy of a request. A request of an untrusted workspace // (WithProjectCodeAllowed) forbids Git, whatever its command. A Git request of a context with // a console also asks Core to report the internal queries of the categories the console -// records, names the category the context gives, and marks an automatic refresh. A request -// with nothing to ask keeps Core's defaults. +// records, names the category the context gives, and marks an automatic refresh. A Git request +// of a context that can ask the user (WithGitAuthentication) is interactive, unless it is an +// automatic refresh, which never asks. A request with nothing to ask keeps Core's defaults. func gitExecutionOf(ctx context.Context, command string) *gitExecution { - var execution gitExecution + refresh, _ := ctx.Value(gitRefreshKey{}).(bool) + execution := gitExecution{Interactive: !refresh && gitAuthenticationOf(ctx, command) != nil} if allowed, _ := ctx.Value(projectCodeAllowedKey{}).(func() bool); allowed != nil && !allowed() { execution.ProjectCodeAllowed = new(false) } @@ -849,11 +851,11 @@ func gitExecutionOf(ctx context.Context, command string) *gitExecution { if len(execution.ConsoleQueries) > 0 { execution.QueryCategory, _ = ctx.Value(gitQueryCategoryKey{}).(GitQueryCategory) } - if refresh, _ := ctx.Value(gitRefreshKey{}).(bool); refresh { + if refresh { execution.Source = "background" } } - if len(execution.ConsoleQueries) == 0 && execution.Source == "" && execution.ProjectCodeAllowed == nil { + if len(execution.ConsoleQueries) == 0 && execution.Source == "" && execution.ProjectCodeAllowed == nil && !execution.Interactive { return nil } return &execution diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 6288bcaa1..e329e5a92 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -916,6 +916,17 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.git.worktrees.lockedBecause": "Locked: {reason}", "desktop.git.worktrees.removed": "Removed worktree '{name}'", "desktop.git.yesterday": "Yesterday", + "desktop.gitAuth.again": "Asked again (attempt {attempt}): the previous answer did not work.", + "desktop.gitAuth.answer": "Answer", + "desktop.gitAuth.cancel": "Cancel", + "desktop.gitAuth.directory": "Asked by Git in {path}", + "desktop.gitAuth.failed": "Could not pass the answer to Git: {reason}", + "desktop.gitAuth.refused": "Git did not accept the answer: an answer is at most 8192 bytes and has no line breaks. The question was cancelled.", + "desktop.gitAuth.retry": "Retry", + "desktop.gitAuth.retryMessage": "Git could not authenticate with the remote. Retry once and type the credentials in Lithe instead of using the credential helper?", + "desktop.gitAuth.secretHint": "The answer goes to this Git process only. Lithe does not save it.", + "desktop.gitAuth.submit": "OK", + "desktop.gitAuth.title": "Git Authentication", "desktop.gitHistory.cherryPicked": "Cherry-picked {hash} onto the current branch", "desktop.gitHistory.deleteCommit": "Delete Commit…", "desktop.gitHistory.resetDone": "Reset the current branch to {hash}", @@ -4214,6 +4225,17 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.git.worktrees.lockedBecause": "已锁定:{reason}", "desktop.git.worktrees.removed": "已删除工作树“{name}”", "desktop.git.yesterday": "昨天", + "desktop.gitAuth.again": "第 {attempt} 次询问:上一次的回答没有通过。", + "desktop.gitAuth.answer": "回答", + "desktop.gitAuth.cancel": "取消", + "desktop.gitAuth.directory": "Git 在 {path} 中询问", + "desktop.gitAuth.failed": "无法把回答交给 Git:{reason}", + "desktop.gitAuth.refused": "Git 没有接受这个回答:回答最多 8192 字节,且不能包含换行。这个问题已取消。", + "desktop.gitAuth.retry": "重试", + "desktop.gitAuth.retryMessage": "Git 没有通过远程仓库的身份验证。要重试一次,并改为在 Lithe 中输入凭据(不使用凭据助手)吗?", + "desktop.gitAuth.secretHint": "回答只交给这个 Git 进程,Lithe 不会保存。", + "desktop.gitAuth.submit": "确定", + "desktop.gitAuth.title": "Git 身份验证", "desktop.gitHistory.cherryPicked": "已将 {hash} 拣选到当前分支", "desktop.gitHistory.deleteCommit": "删除提交…", "desktop.gitHistory.resetDone": "已将当前分支重置到 {hash}", diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 4c5d98b31..5b29c95bf 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -207,6 +207,7 @@ type Kernel interface { GitDeleteBranch(ctx context.Context, root string, branch core.GitReference) (core.GitBranchDeletion, error) GitForceDeleteBranch(ctx context.Context, root string, branch core.GitReference, expectedTarget string) (core.GitBranchDeletion, error) GitDeleteRemoteBranch(ctx context.Context, root string, reference core.GitReference) error + GitAuthRespond(ctx context.Context, requestID string, answer *string) (bool, error) GitCreateTag(ctx context.Context, root, name, revision, message string) error GitRebasePreview(ctx context.Context, root, base string) (core.RebasePreview, error) GitRebaseStart(ctx context.Context, root string, preview core.RebasePreview, steps []core.RebaseStep) (*core.RebaseSession, error) @@ -763,8 +764,10 @@ type App struct { // semantics: back/forward history, the outline, references and so on (editor_features.go). editor editorFeatures - welcome welcomeState - clone cloneState + welcome welcomeState + clone cloneState + // gitAuth holds the questions of the Git operations the user started (git_auth.go). + gitAuth gitAuthState newProject newProjectState // generatorPlugins, projectToolLists and projectCommand replace the plugin // service, the toolchain discovery and the PATH lookup the New Project window diff --git a/desktop/internal/workbench/branch_delete.go b/desktop/internal/workbench/branch_delete.go index 73b720658..e20a58758 100644 --- a/desktop/internal/workbench/branch_delete.go +++ b/desktop/internal/workbench/branch_delete.go @@ -117,6 +117,10 @@ func (a *App) confirmDelete(p *project) { kernel := a.kernel results := make([]branchDeletion, len(branches)) a.background(p, timeout, func(ctx context.Context) func(*App) { + if remote { + // The push that deletes a remote branch may ask for credentials. + ctx = a.gitAuthentication(ctx) + } for i, r := range branches { if force { deleted, err := kernel.GitForceDeleteBranch(ctx, root, r, reviews[i].target) diff --git a/desktop/internal/workbench/clone.go b/desktop/internal/workbench/clone.go index 9a07c73f5..0f9bf0ace 100644 --- a/desktop/internal/workbench/clone.go +++ b/desktop/internal/workbench/clone.go @@ -122,7 +122,7 @@ func (a *App) submitClone() { kernel := a.kernel a.background(nil, 0, func(context.Context) func(*App) { defer cancel() - err := kernel.GitClone(ctx, parent, source, destination) + err := kernel.GitClone(a.gitAuthentication(ctx), parent, source, destination) return func(a *App) { c := &a.clone if !c.open || c.generation != generation { diff --git a/desktop/internal/workbench/commit.go b/desktop/internal/workbench/commit.go index c973a67fe..08e9a4a5d 100644 --- a/desktop/internal/workbench/commit.go +++ b/desktop/internal/workbench/commit.go @@ -352,6 +352,8 @@ func (a *App) runCommit(p *project, t commitTarget, session core.WorkspaceCommit } kernel := a.kernel a.background(p, commitRunTimeout, func(ctx context.Context) func(*App) { + // A push step may ask for credentials. + ctx = a.gitAuthentication(ctx) var err error for !session.Finished { next, stepErr := kernel.WorkspaceCommitStep(ctx, session) diff --git a/desktop/internal/workbench/git_auth.go b/desktop/internal/workbench/git_auth.go new file mode 100644 index 000000000..8c22dc7f7 --- /dev/null +++ b/desktop/internal/workbench/git_auth.go @@ -0,0 +1,180 @@ +package workbench + +import ( + "context" + "slices" + "strconv" + "strings" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/ui" +) + +// Git authentication: a Git operation the user started (a fetch, pull, push, clone, or the +// checkout of a pull request) may ask for a user name, a password, token or passphrase, or, +// after its transfer failed to authenticate, whether to retry it once with credentials typed +// here instead of the credential helper (core.WithGitAuthentication). The questions queue in +// the order Git asked them. One dialog, over everything else, answers the first, and the next +// follows; a question leaves the queue once it is answered or its request has returned. + +const ( + // gitAuthRespondTimeout bounds passing one answer to Core, which replies at once. + gitAuthRespondTimeout = 10 * time.Second + // gitAuthDialogWidth is the width of the dialog: room for Git's question with a URL. + gitAuthDialogWidth = 480 +) + +// gitAuthState is what the window keeps of the questions Git is waiting on. +type gitAuthState struct { + // queue is every question still waiting, the first asked first. + queue []core.GitAuthChallenge + // field holds what is typed for queue[0]. Each question gets a field of its own (fieldFor + // names it), so neither an answer nor its undo history outlives the question. + field ui.Field + fieldFor string + // open is the dialog's flag; the dialog is open while the queue is not empty. + open bool +} + +// gitAuthentication returns ctx with this window as the prompt for the questions of the Git +// operation it carries. Give it only to an operation the user started, never to an automatic +// refresh: Core lets that one fail instead of asking. The prompt runs on the request's +// goroutine, so it only posts the question to the window thread, and posts its removal once the +// request has returned. +func (a *App) gitAuthentication(ctx context.Context) context.Context { + return core.WithGitAuthentication(ctx, func(challenge core.GitAuthChallenge) { + a.post(func(a *App) { a.gitAuth.queue = append(a.gitAuth.queue, challenge) }) + go func() { + <-challenge.Done + a.post(func(a *App) { a.dropGitAuth(challenge.RequestID) }) + }() + }) +} + +// dropGitAuth removes the question requestID, whose request has returned, with what was typed +// for it. +func (a *App) dropGitAuth(requestID string) { + g := &a.gitAuth + g.queue = slices.DeleteFunc(g.queue, func(challenge core.GitAuthChallenge) bool { return challenge.RequestID == requestID }) + if g.fieldFor == requestID { + g.field, g.fieldFor = ui.Field{}, "" + } +} + +// gitAuthDialog declares the dialog that answers the first waiting question. Git's or SSH's own +// question is upstream text, shown as Core redacted it; the question whether to retry is +// Lithe's own and is translated. Dismissing the dialog cancels the question, which fails the +// operation that asked. +func (a *App) gitAuthDialog(c ui.C) { + g := &a.gitAuth + if len(g.queue) == 0 { + return + } + head := g.queue[0] + if g.fieldFor != head.RequestID { + g.field, g.fieldFor = ui.Field{}, head.RequestID + } + lang := a.language() + g.open = true + submitted, cancelled, confirmed := false, false, false + closed := ui.ModalWith(c, &g.open, i18n.Shared(lang, "desktop.gitAuth.title"), ui.ModalSpec{Width: gitAuthDialogWidth}, func() { + ui.Column(c).FillWidth().Gap(10).Children(func() { + if head.Retry { + ui.Wrap(c, i18n.Shared(lang, "desktop.gitAuth.retryMessage")) + } else { + ui.Wrap(c, strings.TrimSpace(head.Prompt)) + if head.Attempt > 1 { + ui.Wrap(c, i18n.SharedFormat(lang, "desktop.gitAuth.again", map[string]string{"attempt": strconv.Itoa(head.Attempt)})). + FontSize(12).Color(a.colors.Warning) + } + // The field is the question's own part, so it takes the focus again for the next + // question as it appears. + field := ui.TextField(c.Part(head.RequestID), &g.field, i18n.Shared(lang, "desktop.gitAuth.answer"), "").FillWidth().AutoFocus() + if head.Secret { + field = field.Secure() + } + submitted = field.Submitted() + if head.Secret { + ui.Wrap(c, i18n.Shared(lang, "desktop.gitAuth.secretHint")).FontSize(12).Color(a.colors.Subtle) + } + } + if head.WorkingDirectory != "" { + ui.Wrap(c, i18n.SharedFormat(lang, "desktop.gitAuth.directory", map[string]string{"path": head.WorkingDirectory})). + FontSize(12).Color(a.colors.Subtle) + } + }) + }, func() { + cancelled = ui.Button(c, i18n.Shared(lang, "desktop.gitAuth.cancel")).Outline().Clicked() + label := i18n.Shared(lang, "desktop.gitAuth.submit") + if head.Retry { + label = i18n.Shared(lang, "desktop.gitAuth.retry") + } + confirmed = ui.Button(c, label).Clicked() + }) + switch { + case closed || cancelled: + c.After(func() { a.answerGitAuth(head.RequestID, false) }) + case confirmed || submitted: + c.After(func() { a.answerGitAuth(head.RequestID, true) }) + } +} + +// answerGitAuth answers the question requestID if it is still the first: with what was typed, +// or with core.GitRetryAnswer for the retry question, when confirm is set, and otherwise cancels +// it. The question leaves the queue at once; Core's verdict arrives later. An answer Core no +// longer takes is for a question that expired or whose request returned, and the dialog has +// moved on; an answer Core refused, too long or with a line break, cancels the question and +// says why. +func (a *App) answerGitAuth(requestID string, confirm bool) { + g := &a.gitAuth + if len(g.queue) == 0 || g.queue[0].RequestID != requestID { + return + } + head := g.queue[0] + g.queue = g.queue[1:] + var answer *string + action := "git.authentication.cancel" + switch { + case confirm && head.Retry: + retry := core.GitRetryAnswer + answer, action = &retry, "git.authentication.retry" + case confirm: + typed := g.field.Text() + answer, action = &typed, "git.authentication.answer" + } + g.field, g.fieldFor = ui.Field{}, "" + a.performed(action, surfaceButton) + kernel := a.kernel + a.background(nil, gitAuthRespondTimeout, func(ctx context.Context) func(*App) { + accepted, err := kernel.GitAuthRespond(ctx, head.RequestID, answer) + refused := false + if err == nil && !accepted && answer != nil && !requestReturned(head.Done) { + // Core took no answer although the request still runs: either it refused this one + // or the question expired. Only a question that still waits accepts the cancel. + refused, err = kernel.GitAuthRespond(ctx, head.RequestID, nil) + } + return func(a *App) { + lang := a.language() + switch { + case err != nil: + a.operationFailed("git_authentication", err) + a.notifyError(i18n.SharedFormat(lang, "desktop.gitAuth.failed", map[string]string{"reason": err.Error()})) + case refused: + a.operationRejected("git_authentication", "answer_refused") + a.notifyError(i18n.Shared(lang, "desktop.gitAuth.refused")) + } + } + }) +} + +// requestReturned reports whether done, the Done of a challenge, has been closed. +func requestReturned(done <-chan struct{}) bool { + select { + case <-done: + return true + default: + return false + } +} diff --git a/desktop/internal/workbench/git_auth_test.go b/desktop/internal/workbench/git_auth_test.go new file mode 100644 index 000000000..b17f8ef40 --- /dev/null +++ b/desktop/internal/workbench/git_auth_test.go @@ -0,0 +1,307 @@ +package workbench + +import ( + "context" + "errors" + "io/fs" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/gfx" +) + +// refusingRemote is a Git HTTP remote that refuses every request with a Basic challenge and +// records the credentials each request carried. +type refusingRemote struct { + url string + mu sync.Mutex + credentials []string +} + +func newRefusingRemote(t *testing.T) *refusingRemote { + t.Helper() + remote := &refusingRemote{} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if user, password, ok := r.BasicAuth(); ok { + remote.mu.Lock() + remote.credentials = append(remote.credentials, user+":"+password) + remote.mu.Unlock() + } + w.Header().Set("WWW-Authenticate", `Basic realm="lithe-test"`) + http.Error(w, "authentication required", http.StatusUnauthorized) + })) + t.Cleanup(server.Close) + // A proxy of the host must not stand between Git and the local server. + t.Setenv("no_proxy", "*") + t.Setenv("NO_PROXY", "*") + remote.url = server.URL + "/repository.git" + return remote +} + +func (r *refusingRemote) received() []string { + r.mu.Lock() + defer r.mu.Unlock() + return slices.Clone(r.credentials) +} + +// key presses key in the window and paints what it did, without waiting for the background +// work it started: a Git operation that asks stays running until the question is answered. +func (h *harness) key(key gfx.Key) { + h.t.Helper() + if err := h.driver.Key(key, 0); err != nil { + h.t.Fatal(err) + } + if err := h.driver.Pump(); err != nil { + h.t.Fatal(err) + } +} + +// typeText types value into the focused field and paints it. +func (h *harness) typeText(value string) { + h.t.Helper() + if err := h.driver.Type(value); err != nil { + h.t.Fatal(err) + } + if err := h.driver.Pump(); err != nil { + h.t.Fatal(err) + } +} + +// awaitGitQuestion waits until the window shows a question that asked holds and paints it +// with the field focused. +func (h *harness) awaitGitQuestion(what string, asked func(core.GitAuthChallenge) bool) core.GitAuthChallenge { + h.t.Helper() + h.await(what, func() bool { return len(h.app.gitAuth.queue) > 0 && asked(h.app.gitAuth.queue[0]) }) + for range 2 { + if err := h.driver.Pump(); err != nil { + h.t.Fatal(err) + } + } + return h.app.gitAuth.queue[0] +} + +// gitAuthActions are the answers the window logged as performed, in order. +func gitAuthActions(logger *treeRecordingLog) []string { + logger.mu.Lock() + defer logger.mu.Unlock() + var actions []string + for _, event := range logger.events { + if action, _ := event.Fields["action"].(string); event.Event == "app.action.performed" && strings.HasPrefix(action, "git.authentication.") { + actions = append(actions, event.Fields["action"].(string)) + } + } + return actions +} + +// A clone the user started asks for the user name and the password in the window, through the +// real Core and Git: the password field hides what is typed, both answers reach the remote, and +// cancelling the question whether to retry ends the clone with its failure in the dialog. +func TestCloneAsksForCredentialsInTheWindow(t *testing.T) { + requireTestGit(t) + remote := newRefusingRemote(t) + h := newHarnessWithLanguages(t, &gitKernel{Client: core.NewClient()}, []string{"en-US"}) + logger := &treeRecordingLog{} + h.app.logSink = logger + lang := h.app.language() + parent := t.TempDir() + h.app.openClone(surfaceButton) + h.app.clone.source.SetText(remote.url) + h.app.clone.parent.SetText(parent) + h.app.clone.name.SetText("project") + h.app.submitClone() + + user := h.awaitGitQuestion("the user name question", func(c core.GitAuthChallenge) bool { return !c.Secret && !c.Retry }) + if !h.shows("Username for") || !h.showsWrapped(i18n.SharedFormat(lang, "desktop.gitAuth.directory", map[string]string{"path": user.WorkingDirectory})) { + t.Fatal("the dialog does not show Git's question and where it runs") + } + if got := h.focusedName(); got != i18n.Shared(lang, "desktop.gitAuth.answer") { + t.Fatalf("focused %q, want the answer field", got) + } + h.typeText("alice") + if !h.shows("alice") { + t.Fatal("the user name field does not show what is typed") + } + h.key(gfx.KeyEnter) + + h.awaitGitQuestion("the password question", func(c core.GitAuthChallenge) bool { return c.Secret }) + if !h.shows("Password for") || h.shows("alice") || !h.showsWrapped(i18n.Shared(lang, "desktop.gitAuth.secretHint")) { + t.Fatal("the password dialog does not show Git's question alone with the note that the answer is not kept") + } + if got := h.focusedName(); got != i18n.Shared(lang, "desktop.gitAuth.answer") { + t.Fatalf("focused %q, want the new answer field", got) + } + h.typeText("s3cret") + if h.shows("s3cret") { + t.Fatal("the password field shows what is typed") + } + h.key(gfx.KeyEnter) + + h.awaitGitQuestion("the question whether to retry", func(c core.GitAuthChallenge) bool { return c.Retry }) + if !h.showsWrapped(i18n.Shared(lang, "desktop.gitAuth.retryMessage")) { + t.Fatal("the retry question is not the translated one") + } + // Escape dismisses the topmost dialog, the question, and leaves the clone dialog alone. + h.key(gfx.KeyEscape) + if h.app.clone.cancelling || !h.app.clone.open { + t.Fatal("Escape reached the clone dialog instead of the question") + } + h.await("the clone to fail", func() bool { return !h.app.clone.busy }) + h.settle() + if h.app.clone.err == "" || h.app.project != nil || len(h.app.gitAuth.queue) != 0 { + t.Fatalf("clone error = %q, project = %v, waiting = %d, want the failure and nothing waiting", h.app.clone.err, h.app.project, len(h.app.gitAuth.queue)) + } + if got, want := remote.received(), []string{"alice:s3cret"}; !slices.Equal(got, want) { + t.Fatalf("remote received %q, want %q", got, want) + } + want := []string{"git.authentication.answer", "git.authentication.answer", "git.authentication.cancel"} + if got := gitAuthActions(logger); !slices.Equal(got, want) { + t.Fatalf("performed %q, want %q", got, want) + } + if _, err := os.Stat(filepath.Join(parent, "project")); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("the failed clone left its destination behind: %v", err) + } +} + +// gitAuthKernel answers git.authRespond with accept and records what it was sent. +type gitAuthKernel struct { + *testKernel + accept func(answer *string) bool + mu sync.Mutex + answers []string +} + +const cancelAnswer = "" + +func (k *gitAuthKernel) GitAuthRespond(_ context.Context, _ string, answer *string) (bool, error) { + k.mu.Lock() + defer k.mu.Unlock() + if answer == nil { + k.answers = append(k.answers, cancelAnswer) + } else { + k.answers = append(k.answers, *answer) + } + return k.accept(answer), nil +} + +func (k *gitAuthKernel) sent() []string { + k.mu.Lock() + defer k.mu.Unlock() + return slices.Clone(k.answers) +} + +// gitAuthHarness is a window whose kernel answers git.authRespond with accept and that waits +// on challenges. +func gitAuthHarness(t *testing.T, accept func(*string) bool, challenges ...core.GitAuthChallenge) (*harness, *gitAuthKernel, *treeRecordingLog) { + t.Helper() + kernel := &gitAuthKernel{testKernel: &testKernel{Client: core.NewClient()}, accept: accept} + h := newHarnessWithLanguages(t, kernel, []string{"en-US"}) + logger := &treeRecordingLog{} + h.app.logSink = logger + h.app.gitAuth.queue = challenges + h.app.invalidator.Invalidate() + h.settle() + h.settle() + return h, kernel, logger +} + +// An answer Core does not take while the request still runs is cancelled: if the cancel is +// taken, Core refused the answer and the window says why; if not, the question had expired and +// nothing is said. An answer to a question whose request returned is not followed up. +func TestGitAuthAnswerCoreDidNotTake(t *testing.T) { + running := make(chan struct{}) + returned := make(chan struct{}) + close(returned) + refusedNotice := i18n.Shared(i18n.English, "desktop.gitAuth.refused") + cases := []struct { + name string + done chan struct{} + accept func(*string) bool + sent []string + notice bool + }{ + {"refused", running, func(answer *string) bool { return answer == nil }, []string{"token", cancelAnswer}, true}, + {"expired", running, func(*string) bool { return false }, []string{"token", cancelAnswer}, false}, + {"returned", returned, func(*string) bool { return false }, []string{"token"}, false}, + {"accepted", running, func(*string) bool { return true }, []string{"token"}, false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + h, kernel, logger := gitAuthHarness(t, c.accept, core.GitAuthChallenge{ + RequestID: "r1", Prompt: "Password for 'https://example.invalid': ", Secret: true, Attempt: 1, Done: c.done, + }) + if got := h.focusedName(); got != i18n.Shared(i18n.English, "desktop.gitAuth.answer") { + t.Fatalf("focused %q, want the answer field", got) + } + h.typeText("token") + h.key(gfx.KeyEnter) + h.settle() + if got := kernel.sent(); !slices.Equal(got, c.sent) { + t.Fatalf("sent %q, want %q", got, c.sent) + } + if len(h.app.gitAuth.queue) != 0 || h.app.gitAuth.field.Text() != "" { + t.Fatal("the answered question or its answer stayed in the window") + } + if got := h.app.notice == refusedNotice; got != c.notice { + t.Fatalf("notice = %q, want the refusal = %v", h.app.notice, c.notice) + } + logger.mu.Lock() + rejected := slices.ContainsFunc(logger.events, func(event core.LogEvent) bool { + return event.Event == operationRejectedEvent && event.Fields["operation"] == "git_authentication" && event.Fields["reason"] == "answer_refused" + }) + logger.mu.Unlock() + if rejected != c.notice { + t.Fatalf("logged the refusal = %v, want %v", rejected, c.notice) + } + }) + } +} + +// Questions are answered in the order they were asked, each with a field of its own: one whose +// request returned leaves with what was typed for it, the retry question answers with +// core.GitRetryAnswer, and dismissing the dialog cancels. +func TestGitAuthQuestionsQueueInOrder(t *testing.T) { + running := make(chan struct{}) + h, kernel, logger := gitAuthHarness(t, func(*string) bool { return true }, + core.GitAuthChallenge{RequestID: "r1", Prompt: "Username for 'https://one.invalid': ", Attempt: 1, Done: running}, + core.GitAuthChallenge{RequestID: "r2", Prompt: "Enter passphrase for key '/k': ", Secret: true, Attempt: 2, Done: running}, + core.GitAuthChallenge{RequestID: "r3", Prompt: "Retry", Retry: true, Attempt: 2, Done: running}, + core.GitAuthChallenge{RequestID: "r4", Prompt: "Username for 'https://four.invalid': ", Attempt: 1, Done: running}, + ) + if !h.shows("Username for 'https://one.invalid':") || h.shows("passphrase") { + t.Fatal("the dialog does not show the first question alone") + } + h.typeText("alice") + // The request of the first question returns: gitAuthentication posts the drop like this. + h.app.post(func(a *App) { a.dropGitAuth("r1") }) + h.settle() + if h.app.gitAuth.field.Text() != "" { + t.Fatal("the answer to a question whose request returned stayed in the window") + } + if !h.shows("Enter passphrase for key") || h.shows("alice") || !h.showsWrapped(i18n.SharedFormat(i18n.English, "desktop.gitAuth.again", map[string]string{"attempt": "2"})) { + t.Fatal("the passphrase question asked again does not show alone with the note that it is asked again") + } + h.typeText("phrase") + h.key(gfx.KeyEnter) + h.settle() + h.clickLabeled(i18n.Shared(i18n.English, "desktop.gitAuth.retry")) + h.key(gfx.KeyEscape) + h.settle() + if got, want := kernel.sent(), []string{"phrase", core.GitRetryAnswer, cancelAnswer}; !slices.Equal(got, want) { + t.Fatalf("sent %q, want %q", got, want) + } + if len(h.app.gitAuth.queue) != 0 || h.shows(i18n.Shared(i18n.English, "desktop.gitAuth.title")) { + t.Fatal("the dialog stayed after every question was answered") + } + want := []string{"git.authentication.answer", "git.authentication.retry", "git.authentication.cancel"} + if got := gitAuthActions(logger); !slices.Equal(got, want) { + t.Fatalf("performed %q, want %q", got, want) + } +} diff --git a/desktop/internal/workbench/git_auth_visual_test.go b/desktop/internal/workbench/git_auth_visual_test.go new file mode 100644 index 000000000..122734869 --- /dev/null +++ b/desktop/internal/workbench/git_auth_visual_test.go @@ -0,0 +1,82 @@ +//go:build vivahead + +package workbench + +import ( + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +// TestVisualGitAuthentication captures the questions Git asks while a pull of an open project +// authenticates: the user name with what was typed, the password asked again with its input +// hidden, and whether to retry with the credentials typed in Lithe. +func TestVisualGitAuthentication(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + running := make(chan struct{}) + directory := "/Users/dev/Projects/Demo" + states := []struct { + name string + challenge core.GitAuthChallenge + typed string + }{ + {"user", core.GitAuthChallenge{RequestID: "user", Prompt: "Username for 'https://git.example.com': ", Attempt: 1, WorkingDirectory: directory, Done: running}, "alice"}, + {"secret", core.GitAuthChallenge{RequestID: "secret", Prompt: "Password for 'https://alice@git.example.com': ", Secret: true, Attempt: 2, WorkingDirectory: directory, Done: running}, "s3cret"}, + {"retry", core.GitAuthChallenge{RequestID: "retry", Prompt: "Retry", Retry: true, Attempt: 2, WorkingDirectory: directory, Done: running}, ""}, + } + for _, scene := range []struct{ theme, language string }{{"dark", "zh-CN"}, {"light", "en-US"}} { + for _, state := range states { + name := "git-auth-" + state.name + "-" + scene.theme + "-" + scene.language + t.Run(name, func(t *testing.T) { + h, session := visualGitAuthHarness(t, scene.theme, scene.language) + h.app.post(func(a *App) { a.gitAuth.queue = append(a.gitAuth.queue, state.challenge) }) + h.settle() + h.settle() + if state.typed != "" { + h.typeText(state.typed) + } + h.settle() + if err := session.Screenshot(filepath.Join(out, name+".png")); err != nil { + t.Fatal(err) + } + }) + } + } +} + +// visualGitAuthHarness is a 1280×800 window in theme and language with a project open. +func visualGitAuthHarness(t *testing.T, theme, language string) (*harness, *headless.Session) { + t.Helper() + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, map[string]string{"theme": theme}); err != nil { + t.Fatal(err) + } + var session *headless.Session + h := newHarnessWithDriver(t, Options{Kernel: &testKernel{Client: core.NewClient()}, Store: prefs, Languages: []string{language}}, + func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1280, 800 + var err error + session, err = headless.Open(config, nil, headless.Options{Scale: 2}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + root := filepath.Join(t.TempDir(), "Demo") + if err := os.Mkdir(root, 0700); err != nil { + t.Fatal(err) + } + h.open(root) + return h, session +} diff --git a/desktop/internal/workbench/github_create.go b/desktop/internal/workbench/github_create.go index 2d3b3ec2b..a43531ee7 100644 --- a/desktop/internal/workbench/github_create.go +++ b/desktop/internal/workbench/github_create.go @@ -297,13 +297,14 @@ func (a *App) publishCreateBranch(p *project) { cr.busy, cr.err = true, "" a.performed("git.publishBranch", surfaceButton) language := a.language() - a.background(p, gitTimeout, func(ctx context.Context) func(*App) { + // The push waits on the network, and on the user while it asks for credentials, as any push. + a.background(p, syncTimeout, func(ctx context.Context) func(*App) { preview, err := kernel.GitPushPreviewOf(ctx, root, core.GitReference{}, core.GitPushTagsNone, "") if err == nil && preview.TargetKind == "divergent" { err = errPublishDivergent } if err == nil { - err = kernel.GitPush(ctx, root, preview, core.GitPushTagsNone, "", false) + err = kernel.GitPush(a.gitAuthentication(ctx), root, preview, core.GitPushTagsNone, "", false) } var facts core.PullRequestContext if err == nil { diff --git a/desktop/internal/workbench/github_prs.go b/desktop/internal/workbench/github_prs.go index 48af07cc5..8ff8c5646 100644 --- a/desktop/internal/workbench/github_prs.go +++ b/desktop/internal/workbench/github_prs.go @@ -351,8 +351,10 @@ func (a *App) checkoutPullRequest(p *project) { reviewed := *pr.preview pr.busy = true a.performed("github.pullRequest.checkout", surfaceButton) - a.background(p, gitTimeout, func(ctx context.Context) func(*App) { - err := kernel.GitPullRequestCheckout(ctx, root, number, head, reviewed, &repo) + // The checkout fetches the pull request's head, which waits on the network, and on the user + // while it asks for credentials, as any fetch. + a.background(p, syncTimeout, func(ctx context.Context) func(*App) { + err := kernel.GitPullRequestCheckout(a.gitAuthentication(ctx), root, number, head, reviewed, &repo) return func(a *App) { pr := &a.pullRequests pr.busy = false diff --git a/desktop/internal/workbench/gitsync.go b/desktop/internal/workbench/gitsync.go index 7e0914cc4..98555ffd2 100644 --- a/desktop/internal/workbench/gitsync.go +++ b/desktop/internal/workbench/gitsync.go @@ -153,7 +153,8 @@ func (a *App) runSyncAt(p *project, root, operation, label string, failed func(r defer stop() defer context.AfterFunc(op, stop)() ctx = core.WithGitProgress(ctx, func(progress core.GitProgress) { a.postSyncProgress(p, relay, progress) }) - done, err := work(ctx, kernel, root) + // Every sync is one the user started, so its transfer may ask for credentials. + done, err := work(a.gitAuthentication(ctx), kernel, root) readCtx, readCancel := context.WithTimeout(p.ctx, gitTimeout) defer readCancel() generation := p.gitStatusGeneration.Add(1) diff --git a/desktop/internal/workbench/logevents_test.go b/desktop/internal/workbench/logevents_test.go index 34ac764d1..d388a9344 100644 --- a/desktop/internal/workbench/logevents_test.go +++ b/desktop/internal/workbench/logevents_test.go @@ -45,6 +45,11 @@ func TestLogEventsMatchCatalog(t *testing.T) { {operationFailedLevel, operationFailedEvent, operationFailedFields("editor_encoding_reopen", errLossyDecode)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("git_branch_name_preview", failure)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("git_commit", failure)}, + {operationFailedLevel, operationFailedEvent, operationFailedFields("git_authentication", failure)}, + {operationRejectedLevel, operationRejectedEvent, operationRejectedFields("git_authentication", "answer_refused")}, + {core.LevelInfo, "app.action.performed", map[string]any{"action": "git.authentication.answer", "surface": surfaceButton}}, + {core.LevelInfo, "app.action.performed", map[string]any{"action": "git.authentication.retry", "surface": surfaceButton}}, + {core.LevelInfo, "app.action.performed", map[string]any{"action": "git.authentication.cancel", "surface": surfaceButton}}, {operationFailedLevel, operationFailedEvent, operationFailedFields("settings_save", failure)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_reveal_recent", failure)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("editor_open_in_browser", failure)}, diff --git a/desktop/internal/workbench/root.go b/desktop/internal/workbench/root.go index c83965805..37b6d6097 100644 --- a/desktop/internal/workbench/root.go +++ b/desktop/internal/workbench/root.go @@ -299,7 +299,8 @@ func (a *App) runShortcut(id string, view *editorview.View, term *terminal) { // overlays declares everything the window shows over the workbench: the dialogs, the search // and navigation popups, the language popups, the plugin prompts, the import of an -// earlier client's plugin secrets, the Git dialogs and the New Project dialog. Each dialog's +// earlier client's plugin secrets, the Git dialogs, the New Project dialog and the questions +// Git asks while it authenticates. Each dialog's // state stays with its own file; the toasts are declared last, over all of them. func (a *App) overlays(c ui.C) { a.scratchPopup(c) @@ -336,6 +337,9 @@ func (a *App) overlays(c ui.C) { a.newProjectModal(c) // The update dialog shows on the welcome screen as on a project, over whatever is open. a.updateDialog(c) + // A Git question holds up the operation that asked it, which may have any dialog open, so + // it shows over all of them. + a.gitAuthDialog(c) } // dragLayer declares what a drag in progress paints over the workbench: the zones and diff --git a/desktop/internal/workbench/settings_toolchains_test.go b/desktop/internal/workbench/settings_toolchains_test.go index 23b8c68d7..51bff9975 100644 --- a/desktop/internal/workbench/settings_toolchains_test.go +++ b/desktop/internal/workbench/settings_toolchains_test.go @@ -265,6 +265,11 @@ func TestToolchainSettingsReadbackFailureReportsCommittedSource(t *testing.T) { const syntheticWorkbenchInterpMarkerEnv = "LITHE_TEST_SYNTHETIC_INTERP_MARKER" func TestMain(m *testing.M) { + // Core names the running executable as the AskPass helper of an interactive Git command, + // so a test that lets Git ask starts this binary in helper mode; it must not run the tests. + if prompt, helper := core.GitAskPassRequest(os.Args); helper { + os.Exit(core.GitAskPass(prompt)) + } if maybeRunBuildProbeHelper() { return } diff --git a/docs/assets/git-askpass/git-auth-retry-dark-zh-CN.png b/docs/assets/git-askpass/git-auth-retry-dark-zh-CN.png new file mode 100644 index 000000000..118fe90eb Binary files /dev/null and b/docs/assets/git-askpass/git-auth-retry-dark-zh-CN.png differ diff --git a/docs/assets/git-askpass/git-auth-retry-light-en-US.png b/docs/assets/git-askpass/git-auth-retry-light-en-US.png new file mode 100644 index 000000000..ba4b55903 Binary files /dev/null and b/docs/assets/git-askpass/git-auth-retry-light-en-US.png differ diff --git a/docs/assets/git-askpass/git-auth-secret-dark-zh-CN.png b/docs/assets/git-askpass/git-auth-secret-dark-zh-CN.png new file mode 100644 index 000000000..ddc017c03 Binary files /dev/null and b/docs/assets/git-askpass/git-auth-secret-dark-zh-CN.png differ diff --git a/docs/assets/git-askpass/git-auth-secret-light-en-US.png b/docs/assets/git-askpass/git-auth-secret-light-en-US.png new file mode 100644 index 000000000..52af9ee64 Binary files /dev/null and b/docs/assets/git-askpass/git-auth-secret-light-en-US.png differ diff --git a/docs/assets/git-askpass/git-auth-user-dark-zh-CN.png b/docs/assets/git-askpass/git-auth-user-dark-zh-CN.png new file mode 100644 index 000000000..c2da073bd Binary files /dev/null and b/docs/assets/git-askpass/git-auth-user-dark-zh-CN.png differ diff --git a/docs/assets/git-askpass/git-auth-user-light-en-US.png b/docs/assets/git-askpass/git-auth-user-light-en-US.png new file mode 100644 index 000000000..9e3409ae0 Binary files /dev/null and b/docs/assets/git-askpass/git-auth-user-light-en-US.png differ diff --git a/shared/i18n/features/git-authentication.json b/shared/i18n/features/git-authentication.json new file mode 100644 index 000000000..187a1f24a --- /dev/null +++ b/shared/i18n/features/git-authentication.json @@ -0,0 +1,119 @@ +{ + "schemaVersion": 1, + "messages": [ + { + "id": "desktop.gitAuth.title", + "description": "Git authentication dialog: title while a Git process the user started waits for an answer", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.gitAuth.directory", + "description": "Git authentication dialog: the folder the asking Git process runs in", + "platforms": [ + "desktop" + ], + "parameters": { + "path": "string" + } + }, + { + "id": "desktop.gitAuth.again", + "description": "Git authentication dialog: Git or SSH asks the same question again because the previous answer did not work (attempt is at least 2)", + "platforms": [ + "desktop" + ], + "parameters": { + "attempt": "string" + } + }, + { + "id": "desktop.gitAuth.answer", + "description": "Git authentication dialog: accessible label of the field the answer is typed into", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.gitAuth.secretHint", + "description": "Git authentication dialog: note under a password, token or passphrase field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.gitAuth.cancel", + "description": "Git authentication dialog: button that cancels the question, which fails the Git operation", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.gitAuth.submit", + "description": "Git authentication dialog: button that passes the typed answer to Git", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.gitAuth.retryMessage", + "description": "Git authentication dialog: question after a fetch, pull, push or clone failed to authenticate, whether to run it once more with credentials typed in Lithe", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.gitAuth.retry", + "description": "Git authentication dialog: button that runs the failed transfer once more and asks for the credentials in Lithe", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.gitAuth.refused", + "description": "Git authentication: notice after Core refused the typed answer, which also cancelled the question", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.gitAuth.failed", + "description": "Git authentication: notice after the answer could not be passed to Core", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + } + ], + "locales": { + "en-US": { + "desktop.gitAuth.title": "Git Authentication", + "desktop.gitAuth.directory": "Asked by Git in {path}", + "desktop.gitAuth.again": "Asked again (attempt {attempt}): the previous answer did not work.", + "desktop.gitAuth.answer": "Answer", + "desktop.gitAuth.secretHint": "The answer goes to this Git process only. Lithe does not save it.", + "desktop.gitAuth.cancel": "Cancel", + "desktop.gitAuth.submit": "OK", + "desktop.gitAuth.retryMessage": "Git could not authenticate with the remote. Retry once and type the credentials in Lithe instead of using the credential helper?", + "desktop.gitAuth.retry": "Retry", + "desktop.gitAuth.refused": "Git did not accept the answer: an answer is at most 8192 bytes and has no line breaks. The question was cancelled.", + "desktop.gitAuth.failed": "Could not pass the answer to Git: {reason}" + }, + "zh-CN": { + "desktop.gitAuth.title": "Git 身份验证", + "desktop.gitAuth.directory": "Git 在 {path} 中询问", + "desktop.gitAuth.again": "第 {attempt} 次询问:上一次的回答没有通过。", + "desktop.gitAuth.answer": "回答", + "desktop.gitAuth.secretHint": "回答只交给这个 Git 进程,Lithe 不会保存。", + "desktop.gitAuth.cancel": "取消", + "desktop.gitAuth.submit": "确定", + "desktop.gitAuth.retryMessage": "Git 没有通过远程仓库的身份验证。要重试一次,并改为在 Lithe 中输入凭据(不使用凭据助手)吗?", + "desktop.gitAuth.retry": "重试", + "desktop.gitAuth.refused": "Git 没有接受这个回答:回答最多 8192 字节,且不能包含换行。这个问题已取消。", + "desktop.gitAuth.failed": "无法把回答交给 Git:{reason}" + } + } +} diff --git a/shared/platform-feature-matrix/features/git-authentication-prompts.json b/shared/platform-feature-matrix/features/git-authentication-prompts.json new file mode 100644 index 000000000..5b2172ce3 --- /dev/null +++ b/shared/platform-feature-matrix/features/git-authentication-prompts.json @@ -0,0 +1,29 @@ +{ + "id": "git-authentication-prompts", + "area": "版本控制", + "group": "Git", + "capability": "Git 在窗口中询问用户名、密码、口令和是否重试", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/core/gitauth.go", + "desktop/internal/core/gitauth_test.go", + "desktop/internal/workbench/git_auth.go", + "desktop/internal/workbench/git_auth_test.go", + "desktop/cmd/lithe/main.go" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/core/gitauth.go", + "desktop/internal/workbench/git_auth.go", + "desktop/cmd/lithe/main.go" + ] + }, + "owner": "Git", + "verification": "对一个要求 HTTPS Basic 认证、且没有凭据助手可用的远程仓库分别执行克隆、拉取、推送、删除远程分支和提交并推送:窗口依次询问用户名和密码,密码输入以圆点显示,答案到达远程;凭据被拒后询问是否在 Lithe 中重新输入,取消后操作以失败结束且不留下克隆目录。对带口令的 SSH 私钥执行拉取,确认口令同样在窗口中询问。两个操作同时询问时按顺序逐个显示;操作结束后它的问题自动消失。日志中只有 git.authentication.answer/retry/cancel 动作,不含提示原文、用户名、主机或答案。", + "notes": "Viva:Git 由 Core 以 GIT_ASKPASS/SSH_ASKPASS 指向 lithe 可执行文件的助手模式运行,助手经 Core 的本地连接取回答案;只有用户在窗口中发起的 Git 操作(克隆、拉取/推送/同步、删除远程分支、提交并推送、GitHub 新建仓库和检出 PR)会询问,后台刷新不询问。macOS 用真实 Core 与 Git 对拒绝认证的 HTTP 远程端到端测试通过;Windows 上助手是 GUI 子系统程序,Git 读取其标准输出仍待实机验证。插件 VCS 提供者的认证提示不在本能力范围。" +}