Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6656 fix(daemon): explain why repo checkout auth failed (#7520) (#7524)
Bohan Jiangf7dd08f30476
diff --git a/server/internal/daemon/health.go b/server/internal/daemon/health.goindex 524bb01d85..8923ebfaf4 100644--- a/server/internal/daemon/health.go+++ b/server/internal/daemon/health.go@@ -136,20 +136,130 @@ func (d *Daemon) clearActiveRepoCheckoutTask(token string) {d.repoCheckoutTasksMu.Unlock()}-func (d *Daemon) activeRepoCheckoutTask(r *http.Request) (activeRepoCheckoutTask, bool) {+// repoCheckoutAuthResult distinguishes the two ways /repo/checkout auth fails.+// They look identical to a caller but have completely different fixes, and+// collapsing them into one 401 is what made #7520 take 13 hours to diagnose.+type repoCheckoutAuthResult int++const (+ repoCheckoutAuthOK repoCheckoutAuthResult = iota+ // repoCheckoutAuthNoCredential: the request carried no usable Authorization+ // header. The current CLI always sends one, so in practice this is a+ // `multica` binary older than repoCheckoutMinCLIVersion — a permanent+ // failure that no retry fixes.+ repoCheckoutAuthNoCredential+ // repoCheckoutAuthUnknownCredential: a token was presented but is not bound+ // to a task running in THIS daemon — the task already finished, or the+ // daemon restarted while the agent process kept running.+ repoCheckoutAuthUnknownCredential+)++// repoCheckoutMinCLIVersion is the first release whose `multica repo checkout`+// sends the Authorization header this endpoint requires. The header and the+// check landed in the same commit (#7205), so every older CLI is rejected here+// no matter how healthy the task is.+const repoCheckoutMinCLIVersion = "v0.4.30"++func (d *Daemon) activeRepoCheckoutTask(r *http.Request) (activeRepoCheckoutTask, repoCheckoutAuthResult) {const bearer = "Bearer "header := strings.TrimSpace(r.Header.Get("Authorization"))if !strings.HasPrefix(header, bearer) {- return activeRepoCheckoutTask{}, false+ return activeRepoCheckoutTask{}, repoCheckoutAuthNoCredential}token := strings.TrimSpace(strings.TrimPrefix(header, bearer))if token == "" {- return activeRepoCheckoutTask{}, false+ return activeRepoCheckoutTask{}, repoCheckoutAuthNoCredential}d.repoCheckoutTasksMu.RLock()task, ok := d.repoCheckoutTasks[token]d.repoCheckoutTasksMu.RUnlock()- return task, ok+ if !ok {+ return activeRepoCheckoutTask{}, repoCheckoutAuthUnknownCredential+ }+ return task, repoCheckoutAuthOK+}++// repoCheckoutListBinariesCommand names the platform's "show every copy on+// PATH" command. The whole point of the rejection is that the caller ran the+// wrong binary, so handing them a command their shell does not have just moves+// the dead end.+func repoCheckoutListBinariesCommand() string {+ if runtime.GOOS == "windows" {+ return "where.exe multica"+ }+ return "which -a multica"+}++// repoCheckoutAuthErrorMessage builds the rejection body. It has to be+// self-explanatory: the caller is an agent inside a task, and the CLI prints+// this string as the whole failure. Anything it does not say has to be+// reconstructed from daemon logs the agent cannot read.+//+// Compatibility advice deliberately lives HERE rather than in the CLI. The+// population that hits repoCheckoutAuthNoCredential is, by definition, running+// a CLI too old to have received any client-side fix; the daemon is the only+// component on this path guaranteed to be current.+//+// Every claim here has to survive Windows and Linux as well as macOS, and has+// to be true rather than merely likely — advice that is wrong on the reader's+// platform, or that asserts a version match nobody verified, recreates exactly+// the misdirection this message exists to end.+func (d *Daemon) repoCheckoutAuthErrorMessage(result repoCheckoutAuthResult) string {+ if result == repoCheckoutAuthUnknownCredential {+ return "repo checkout credential is not bound to a task running in this daemon: " ++ "the task it belongs to has already finished, or the daemon restarted after this agent started. " ++ "Repo checkout is only available while the task that owns this workdir is still running."+ }++ var b strings.Builder+ b.WriteString("repo checkout requires an active task credential, and this request carried none. ")+ b.WriteString("The multica CLI has sent that credential since ")+ b.WriteString(repoCheckoutMinCLIVersion)+ b.WriteString(", so this request came from an older `multica` binary")+ if daemonVersion := strings.TrimSpace(d.cfg.CLIVersion); daemonVersion != "" {+ b.WriteString(" (this daemon runs ")+ b.WriteString(daemonVersion)+ b.WriteString(")")+ }+ b.WriteString(" and will fail every time, not intermittently. List every copy on PATH with `")+ b.WriteString(repoCheckoutListBinariesCommand())+ b.WriteString("`, check each one's version, then upgrade the stale one with `multica update`")+ b.WriteString(" — it handles Homebrew and direct installs on every platform.")+ // os.Executable() reports where this process was STARTED from, which is not+ // a promise about the bytes on disk now: the daemon deliberately supports a+ // binary being replaced out of band while a restart is deferred (see+ // trySelfReload). Claiming a version match here could hand a version-skew+ // victim a second stale binary, so state the provenance and let the reader+ // verify the version.+ if selfBin, err := resolveSelfExecutable(); err == nil {+ b.WriteString(" This daemon started from ")+ b.WriteString(selfBin)+ if pending := d.reloadPending(); pending != "" {+ b.WriteString(", whose on-disk copy has since changed (")+ b.WriteString(pending)+ b.WriteString(")")+ }+ b.WriteString("; check that copy's version before running it directly.")+ }+ return b.String()+}++// writeRepoCheckoutAuthError rejects the request and leaves a trace in+// daemon.log. Before this, the 401 branch logged nothing at all, so a failure+// the agent saw on stderr was invisible to whoever went looking for it (#7520).+// The token is never logged: it is a live task credential.+func (d *Daemon) writeRepoCheckoutAuthError(w http.ResponseWriter, result repoCheckoutAuthResult) {+ message := d.repoCheckoutAuthErrorMessage(result)+ reason := "no_credential"+ if result == repoCheckoutAuthUnknownCredential {+ reason = "unknown_credential"+ }+ d.logger.Warn("repo checkout rejected",+ "reason", reason,+ "min_cli_version", repoCheckoutMinCLIVersion,+ "daemon_version", d.cfg.CLIVersion,+ )+ http.Error(w, message, http.StatusUnauthorized)}func authorizeRepoCheckoutWorkDir(activeRoot, requested string) (string, error) {@@ -293,9 +403,9 @@ func (d *Daemon) repoCheckoutHandler() http.HandlerFunc {http.Error(w, "method not allowed", http.StatusMethodNotAllowed)return}- activeTask, ok := d.activeRepoCheckoutTask(r)- if !ok {- http.Error(w, "repo checkout requires an active task credential", http.StatusUnauthorized)+ activeTask, authResult := d.activeRepoCheckoutTask(r)+ if authResult != repoCheckoutAuthOK {+ d.writeRepoCheckoutAuthError(w, authResult)return}diff --git a/server/internal/daemon/health_test.go b/server/internal/daemon/health_test.goindex a9c2cb873c..f260658ae1 100644--- a/server/internal/daemon/health_test.go+++ b/server/internal/daemon/health_test.go@@ -1,8 +1,10 @@package daemonimport (+ "bytes""context""encoding/json"+ "errors""io""log/slog""net/http"@@ -339,6 +341,9 @@ func TestRepoCheckoutUsesTaskScopedProjectRefByDefault(t *testing.T) {}}+// A request with no Authorization header can only come from a CLI older than+// repoCheckoutMinCLIVersion, which is a permanent failure. The rejection has to+// say so: the agent sees this string and nothing else (#7520).func TestRepoCheckoutRejectsMissingTaskCredential(t *testing.T) {t.Parallel()@@ -347,6 +352,8 @@ func TestRepoCheckoutRejectsMissingTaskCredential(t *testing.T) {cache := &recordingRepoCache{lookupPath: "/cache/org/repo.git"}workDir := t.TempDir()d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, workDir, cache)+ var logs bytes.Buffer+ d.logger = captureLogger(&logs)rec := httptest.NewRecorder()body := strings.NewReader(`{"url":"` + repoURL + `","workspace_id":"` + workspaceID + `","workdir":"` + workDir + `","task_id":"task-1"}`)@@ -358,6 +365,120 @@ func TestRepoCheckoutRejectsMissingTaskCredential(t *testing.T) {if got := cache.lastCreateParams(); got != (repocache.WorktreeParams{}) {t.Fatalf("unauthorized checkout reached repo cache: %+v", got)}+ for _, want := range []string{+ repoCheckoutMinCLIVersion,+ repoCheckoutListBinariesCommand(),+ "multica update",+ "v1.0.0",+ } {+ if !strings.Contains(rec.Body.String(), want) {+ t.Fatalf("rejection body missing %q: %s", want, rec.Body.String())+ }+ }+ // The endpoint serves Windows and Linux too, so the self-help commands must+ // not be a macOS/Homebrew recipe. `multica update` resolves the install+ // method itself; a literal `brew upgrade` is unrunnable for most readers.+ if strings.Contains(rec.Body.String(), "brew upgrade") {+ t.Fatalf("rejection body hardcodes a platform-specific upgrade command: %s", rec.Body.String())+ }+ // The silent 401 branch is what made this undiagnosable from daemon.log.+ if !strings.Contains(logs.String(), "repo checkout rejected") || !strings.Contains(logs.String(), "no_credential") {+ t.Fatalf("expected a log line naming the reason, got: %s", logs.String())+ }+ // Asserted explicitly so a later downgrade to Debug — filtered out of+ // daemon.log by default — cannot silently pass this test.+ if !strings.Contains(logs.String(), "level=WARN") {+ t.Fatalf("rejection must be logged at WARN, got: %s", logs.String())+ }+}++// A token that no active task owns is a different failure with a different fix,+// so it must not be reported as (or advised like) a stale-CLI problem.+func TestRepoCheckoutRejectsUnknownTaskCredential(t *testing.T) {+ t.Parallel()++ const workspaceID = "ws-checkout"+ const repoURL = "https://github.com/org/repo.git"+ cache := &recordingRepoCache{lookupPath: "/cache/org/repo.git"}+ workDir := t.TempDir()+ d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, workDir, cache)+ var logs bytes.Buffer+ d.logger = captureLogger(&logs)++ rec := httptest.NewRecorder()+ body := strings.NewReader(`{"url":"` + repoURL + `","workspace_id":"` + workspaceID + `","workdir":"` + workDir + `","task_id":"task-1"}`)+ req := httptest.NewRequest(http.MethodPost, "/repo/checkout", body)+ req.Header.Set("Authorization", "Bearer mat_not_an_active_task")+ d.repoCheckoutHandler().ServeHTTP(rec, req)++ if rec.Code != http.StatusUnauthorized {+ t.Fatalf("expected 401, got %d: %s", rec.Code, rec.Body.String())+ }+ if got := cache.lastCreateParams(); got != (repocache.WorktreeParams{}) {+ t.Fatalf("unauthorized checkout reached repo cache: %+v", got)+ }+ if !strings.Contains(rec.Body.String(), "not bound to a task running in this daemon") {+ t.Fatalf("rejection body should explain the task is gone: %s", rec.Body.String())+ }+ if strings.Contains(rec.Body.String(), "multica update") {+ t.Fatalf("a live CLI must not be told to upgrade: %s", rec.Body.String())+ }+ if !strings.Contains(logs.String(), "unknown_credential") {+ t.Fatalf("expected a WARN naming the reason, got: %s", logs.String())+ }+ // The token is a live task credential and must never reach the log.+ if strings.Contains(logs.String(), "mat_not_an_active_task") {+ t.Fatalf("task credential leaked into daemon.log: %s", logs.String())+ }+}++// The daemon can name where it started from, which narrows the search — but it+// has not probed that file's version, and the daemon explicitly supports the+// binary being replaced out of band. So the message must describe provenance+// and ask the reader to verify, never assert a match.+func TestRepoCheckoutAuthErrorNamesDaemonBinaryWithoutClaimingAMatch(t *testing.T) {+ original := resolveSelfExecutable+ t.Cleanup(func() { resolveSelfExecutable = original })+ resolveSelfExecutable = func() (string, error) { return "/opt/multica/bin/multica", nil }++ d := &Daemon{cfg: Config{CLIVersion: "v0.4.33"}}+ message := d.repoCheckoutAuthErrorMessage(repoCheckoutAuthNoCredential)+ if !strings.Contains(message, "/opt/multica/bin/multica") {+ t.Fatalf("rejection should name the daemon's own binary: %s", message)+ }+ if !strings.Contains(message, "check that copy's version") {+ t.Fatalf("rejection should ask the reader to verify the version: %s", message)+ }+ for _, unwanted := range []string{"version-matched", "matches this daemon"} {+ if strings.Contains(message, unwanted) {+ t.Fatalf("rejection must not assert an unverified version match (%q): %s", unwanted, message)+ }+ }++ resolveSelfExecutable = func() (string, error) { return "", errors.New("unresolvable") }+ if message := d.repoCheckoutAuthErrorMessage(repoCheckoutAuthNoCredential); !strings.Contains(message, repoCheckoutMinCLIVersion) {+ t.Fatalf("rejection must stay useful when the daemon path is unknown: %s", message)+ }+}++// When the daemon already knows its on-disk copy drifted (a reload deferred+// because tasks were running), staying silent would point a version-skew victim+// at a second stale binary.+func TestRepoCheckoutAuthErrorSurfacesDeferredReload(t *testing.T) {+ original := resolveSelfExecutable+ t.Cleanup(func() { resolveSelfExecutable = original })+ resolveSelfExecutable = func() (string, error) { return "/opt/multica/bin/multica", nil }++ d := &Daemon{cfg: Config{CLIVersion: "v0.4.33"}}+ d.setReloadPending("multica binary on disk reports v0.4.20, running v0.4.33")++ message := d.repoCheckoutAuthErrorMessage(repoCheckoutAuthNoCredential)+ if !strings.Contains(message, "on-disk copy has since changed") {+ t.Fatalf("rejection should warn that the daemon's own binary drifted: %s", message)+ }+ if !strings.Contains(message, "reports v0.4.20, running v0.4.33") {+ t.Fatalf("rejection should carry the drift detail the daemon already has: %s", message)+ }}func TestRepoCheckoutRejectsAnotherTaskWorkdir(t *testing.T) {