Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6658 fix(cli): tell a rejected task token to stop, not to sign in again (#7522) (#7532)

Bohan Jiang617d416029a0
diff --git a/server/internal/cli/client.go b/server/internal/cli/client.go
index f819cb0a99..209fd0c930 100644
--- a/server/internal/cli/client.go
+++ b/server/internal/cli/client.go
@@ -61,11 +61,25 @@ type APIClient struct {
OS string
}
+// TaskTokenPrefix marks a task-scoped agent token, as minted by
+// internal/auth.NewAgentTaskToken. A 401 on one is not the "your login
+// expired" that a 401 on a member credential is: the token belongs to a single
+// run and there is no sign-in that brings it back. Why it was rejected is not
+// something the CLI can see — a terminal task is the usual cause, but a
+// malformed token, one sent to the wrong server, and one dropped by an
+// unrelated cleanup all look identical from here.
+const TaskTokenPrefix = "mat_"
+
type HTTPError struct {
Method string
Path string
StatusCode int
Body string
+ // TaskScoped records that the failing request actually carried a
+ // task-scoped `mat_` token. It changes nothing about the request; it only
+ // lets FormatError tell a 401 worth signing in again for from one where
+ // the right move is to stop (GH #7522).
+ TaskScoped bool
}
func (e *HTTPError) Error() string {
@@ -84,9 +98,27 @@ func newHTTPError(method, path string, resp *http.Response) *HTTPError {
Path: path,
StatusCode: resp.StatusCode,
Body: strings.TrimSpace(string(data)),
+ TaskScoped: requestUsedTaskToken(resp),
}
}
+// requestUsedTaskToken reports whether the request that produced resp actually
+// sent a task token.
+//
+// Reading the client's own Token field would be wrong twice over. DownloadFile
+// deliberately sends no Authorization header for an absolute signed URL, so a
+// 401 from object storage would be reported as a rejected task token purely
+// because the client happened to hold a `mat_` token. And Go strips Authorization
+// across a cross-host redirect, so the request that was sent is not always the
+// one the caller built. resp.Request is the request that actually went out,
+// after redirects, which is the only thing this claim can honestly rest on.
+func requestUsedTaskToken(resp *http.Response) bool {
+ if resp == nil || resp.Request == nil {
+ return false
+ }
+ return strings.HasPrefix(resp.Request.Header.Get("Authorization"), "Bearer "+TaskTokenPrefix)
+}
+
// defaultHTTPTimeout is the per-request timeout for the CLI's HTTP client.
// It can be overridden with the MULTICA_HTTP_TIMEOUT environment variable
// (see httpTimeout). 30s is chosen over the historical 15s because complex
@@ -769,6 +801,7 @@ func (c *APIClient) HealthCheck(ctx context.Context) (string, error) {
Path: "/health",
StatusCode: resp.StatusCode,
Body: strings.TrimSpace(string(data)),
+ TaskScoped: requestUsedTaskToken(resp),
}
}
return strings.TrimSpace(string(data)), nil
diff --git a/server/internal/cli/client_test.go b/server/internal/cli/client_test.go
index 64e8775639..e3c25eceb7 100644
--- a/server/internal/cli/client_test.go
+++ b/server/internal/cli/client_test.go
@@ -561,3 +561,67 @@ func TestSetHeaders_AdvertisesStableAttachmentURLs(t *testing.T) {
}
})
}
+
+// TestHTTPErrorTaskScopedFollowsTheRequestNotTheClient wires the credential
+// claim to what actually went out on the wire.
+//
+// Reading the client's Token field instead is wrong in a way a hand-built
+// HTTPError cannot show: DownloadFile deliberately sends no Authorization
+// header for an absolute signed URL, so a 401 from object storage would be
+// reported to an agent as "your task token was rejected, stop" purely because
+// the client happened to hold one.
+func TestHTTPErrorTaskScopedFollowsTheRequestNotTheClient(t *testing.T) {
+ var sawAuth []string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ sawAuth = append(sawAuth, r.Header.Get("Authorization"))
+ w.WriteHeader(http.StatusUnauthorized)
+ _, _ = io.WriteString(w, `{"error":"unauthorized"}`)
+ }))
+ defer srv.Close()
+
+ taskClient := NewAPIClient(srv.URL, "ws-1", TaskTokenPrefix+"0123456789abcdef")
+
+ t.Run("api call sends the task token", func(t *testing.T) {
+ err := taskClient.GetJSON(context.Background(), "/api/me", &struct{}{})
+ var httpErr *HTTPError
+ if !errors.As(err, &httpErr) {
+ t.Fatalf("err = %v, want an *HTTPError", err)
+ }
+ if !httpErr.TaskScoped {
+ t.Error("a 401 on a request that carried the task token must be marked task-scoped")
+ }
+ if got := FormatError(err, false); !strings.Contains(got, "task token") {
+ t.Errorf("message did not use the task-token copy: %q", got)
+ }
+ })
+
+ t.Run("signed absolute URL sends no credential at all", func(t *testing.T) {
+ before := len(sawAuth)
+ _, err := taskClient.DownloadFile(context.Background(), srv.URL+"/signed-object?sig=abc")
+ var httpErr *HTTPError
+ if !errors.As(err, &httpErr) {
+ t.Fatalf("err = %v, want an *HTTPError", err)
+ }
+ if auth := sawAuth[before]; auth != "" {
+ t.Fatalf("DownloadFile sent %q on an absolute URL; the test no longer covers the unauthenticated path", auth)
+ }
+ if httpErr.TaskScoped {
+ t.Error("a 401 from an unauthenticated signed URL must not be reported as a rejected task token")
+ }
+ if got := FormatError(err, false); strings.Contains(got, "task token") {
+ t.Errorf("storage 401 got the task-token copy: %q", got)
+ }
+ })
+
+ t.Run("member token is never task-scoped", func(t *testing.T) {
+ memberClient := NewAPIClient(srv.URL, "ws-1", "mul_0123456789abcdef")
+ err := memberClient.GetJSON(context.Background(), "/api/me", &struct{}{})
+ var httpErr *HTTPError
+ if !errors.As(err, &httpErr) {
+ t.Fatalf("err = %v, want an *HTTPError", err)
+ }
+ if httpErr.TaskScoped {
+ t.Error("a member credential must not be reported as a task token")
+ }
+ })
+}
diff --git a/server/internal/cli/errors.go b/server/internal/cli/errors.go
index 0c83fe8929..c162b13caf 100644
--- a/server/internal/cli/errors.go
+++ b/server/internal/cli/errors.go
@@ -33,12 +33,17 @@ const (
// HTTP status layer.
KindAuthRequired // 401
- KindForbidden // 403
- KindNotFound // 404
- KindConflict // 409
- KindValidation // 400 / 422
- KindRateLimited // 429
- KindServerError // 5xx
+ // KindTaskTokenRejected is a 401 on a task-scoped token. HTTPError.Kind()
+ // never returns it — the status code alone cannot tell the two apart — so
+ // it is selected in userMessage, where the credential the request actually
+ // sent is known. Exit classification is unchanged: still an auth failure.
+ KindTaskTokenRejected
+ KindForbidden // 403
+ KindNotFound // 404
+ KindConflict // 409
+ KindValidation // 400 / 422
+ KindRateLimited // 429
+ KindServerError // 5xx
// Anything we could not classify.
KindUnknown
@@ -80,6 +85,8 @@ func (k ErrorKind) String() string {
return "network_offline"
case KindAuthRequired:
return "auth_required"
+ case KindTaskTokenRejected:
+ return "task_token_rejected"
case KindForbidden:
return "forbidden"
case KindNotFound:
@@ -307,6 +314,10 @@ var kindMessages = map[ErrorKind][2]string{
"Your session has expired or you are not signed in. Run `multica login` to sign in again. On a self-hosted or non-OAuth setup, ask your administrator for valid credentials.",
"登录已过期或尚未登录。请运行 `multica login` 重新登录。自托管或非 OAuth 场景请联系管理员获取有效凭证。",
},
+ KindTaskTokenRejected: {
+ "This task token was rejected and is no longer usable. Stop here: do not retry, and do not fall back to a profile or member credential, because anything done with one would run as that person rather than as this task. Only the runtime that started this task can supply a valid task token.",
+ "这个 task token 已被拒绝,不再可用。请到此为止:不要重试,也不要改用 profile 或成员凭证 —— 用它们执行的任何操作都会以那个成员的身份运行,而不是以这次 task 的身份运行。只有启动这次 task 的运行时才能提供有效的 task token。",
+ },
KindForbidden: {
"You do not have permission to access this resource. Check that you are in the right workspace, or ask an administrator to grant access.",
"无权访问该资源。请确认当前 workspace 是否正确,或联系管理员授予权限。",
@@ -407,6 +418,21 @@ func userMessage(err error, lang Language) string {
var httpErr *HTTPError
if errors.As(err, &httpErr) {
kind := httpErr.Kind()
+ // A 401 on a task token is not a login problem, and the generic copy
+ // below is the wrong instruction for whoever reads it: it says to sign
+ // in again or ask an administrator for valid credentials. An
+ // autonomous agent can act on that, and one did — after its task token
+ // stopped working mid-run it read the daemon owner's profile PAT and
+ // kept going under the member's identity (GH #7522).
+ //
+ // What the copy must not do is guess *why*. The usual cause is the
+ // task reaching a terminal state, but the same 401 covers a malformed
+ // token, one sent to the wrong server, and one dropped by an unrelated
+ // cleanup. "Stop" is true in every one of those cases; "the task
+ // finished" is not.
+ if kind == KindAuthRequired && httpErr.TaskScoped {
+ return messageFor(KindTaskTokenRejected, lang)
+ }
// Validation and conflict errors carry a useful server-provided
// message; surface it instead of the generic line. A body we cannot
// recognize still falls back to the template, so this never dumps a
diff --git a/server/internal/cli/errors_test.go b/server/internal/cli/errors_test.go
index 980c335705..721475964a 100644
--- a/server/internal/cli/errors_test.go
+++ b/server/internal/cli/errors_test.go
@@ -81,8 +81,8 @@ func TestFormatErrorAllKinds(t *testing.T) {
withLang(t, "") // default English
allKinds := []ErrorKind{
KindNetworkTimeout, KindNetworkDNS, KindNetworkRefused, KindNetworkTLS, KindNetworkOffline,
- KindAuthRequired, KindForbidden, KindNotFound, KindConflict, KindValidation,
- KindRateLimited, KindServerError, KindUnknown,
+ KindAuthRequired, KindTaskTokenRejected, KindForbidden, KindNotFound, KindConflict,
+ KindValidation, KindRateLimited, KindServerError, KindUnknown,
}
for _, lang := range []Language{LangEN, LangZH} {
for _, k := range allKinds {
@@ -375,19 +375,20 @@ func withLang(t *testing.T, lang string) {
func TestErrorKindString(t *testing.T) {
cases := map[ErrorKind]string{
- KindNetworkTimeout: "network_timeout",
- KindNetworkDNS: "network_dns",
- KindNetworkRefused: "network_refused",
- KindNetworkTLS: "network_tls",
- KindNetworkOffline: "network_offline",
- KindAuthRequired: "auth_required",
- KindForbidden: "forbidden",
- KindNotFound: "not_found",
- KindConflict: "conflict",
- KindValidation: "validation",
- KindRateLimited: "rate_limited",
- KindServerError: "server_error",
- KindUnknown: "unknown",
+ KindNetworkTimeout: "network_timeout",
+ KindNetworkDNS: "network_dns",
+ KindNetworkRefused: "network_refused",
+ KindNetworkTLS: "network_tls",
+ KindNetworkOffline: "network_offline",
+ KindAuthRequired: "auth_required",
+ KindTaskTokenRejected: "task_token_rejected",
+ KindForbidden: "forbidden",
+ KindNotFound: "not_found",
+ KindConflict: "conflict",
+ KindValidation: "validation",
+ KindRateLimited: "rate_limited",
+ KindServerError: "server_error",
+ KindUnknown: "unknown",
}
seen := map[string]ErrorKind{}
for k, want := range cases {
@@ -405,6 +406,78 @@ func TestErrorKindString(t *testing.T) {
}
}
+// TestFormatErrorRejectedTaskTokenDoesNotSuggestAnotherCredential is GH #7522
+// in one assertion. The generic 401 copy tells the reader to run `multica
+// login` or ask an administrator for valid credentials. That is right for a
+// person and wrong for an agent: after its task token stopped working mid-run,
+// one read the daemon owner's profile PAT and kept working under the member's
+// identity. A 401 on a task token has to read as "stop", never as "find a
+// working credential".
+//
+// It must also not guess why the token was rejected. A terminal task is the
+// usual cause, but the same 401 covers a malformed token, one sent to the wrong
+// server, and one dropped by an unrelated cleanup — so a message that asserts
+// the task finished is a claim the CLI cannot make.
+//
+// The wiring — which requests are marked task-scoped in the first place — is
+// covered by TestHTTPErrorTaskScopedFollowsTheRequestNotTheClient, which drives
+// a real client instead of hand-building the error.
+func TestFormatErrorRejectedTaskTokenDoesNotSuggestAnotherCredential(t *testing.T) {
+ httpErr := &HTTPError{Method: "GET", Path: "/api/me", StatusCode: 401, TaskScoped: true}
+
+ for _, tc := range []struct {
+ lang string
+ want []string
+ refuted []string
+ }{
+ {"en_US.UTF-8",
+ []string{"rejected", "no longer usable", "Stop here", "do not retry",
+ "do not fall back to a profile or member credential"},
+ // No sign-in advice, and no claim about a cause it cannot verify.
+ []string{"multica login", "administrator", "cancelled", "finished", "terminal state"}},
+ {"zh_CN.UTF-8",
+ []string{"已被拒绝", "不再可用", "不要重试", "不要改用 profile 或成员凭证"},
+ []string{"multica login", "管理员", "已完成", "被取消", "终态"}},
+ } {
+ withLang(t, tc.lang)
+ got := FormatError(httpErr, false)
+ for _, sub := range tc.want {
+ if !strings.Contains(got, sub) {
+ t.Errorf("%s: %q missing %q", tc.lang, got, sub)
+ }
+ }
+ for _, sub := range tc.refuted {
+ if strings.Contains(got, sub) {
+ t.Errorf("%s: %q must not contain %q", tc.lang, got, sub)
+ }
+ }
+ }
+
+ // Glossary: an agent execution is `task` in Chinese; 任务 is the product
+ // entity a user files (an issue). Writing this message with 任务 would say
+ // the user's issue was rejected. See conventions.zh.mdx.
+ withLang(t, "zh_CN.UTF-8")
+ zh := FormatError(httpErr, false)
+ if strings.Contains(zh, "任务") {
+ t.Errorf("zh copy used 任务 for an agent execution; it must stay `task`: %q", zh)
+ }
+ if !strings.Contains(zh, "task") {
+ t.Errorf("zh copy dropped the `task` term entirely: %q", zh)
+ }
+
+ // A member 401 is unchanged: that really is an expired login.
+ withLang(t, "en_US.UTF-8")
+ member := FormatError(&HTTPError{Method: "GET", Path: "/api/me", StatusCode: 401}, false)
+ if !strings.Contains(member, "multica login") {
+ t.Errorf("a member 401 should still point at sign-in, got %q", member)
+ }
+
+ // Exit classification is unchanged — still an auth failure.
+ if got := ExitCodeFor(httpErr); got != ExitAuth {
+ t.Errorf("ExitCodeFor(rejected task token) = %d, want %d", got, ExitAuth)
+ }
+}
+
// TestFormatErrorActionableHints locks in the per-status actionable hints
// refined in PR2, in both languages, so a future copy edit can't silently drop
// the actionable guidance.