Skip to content

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

Go

fix(avatar): serve avatars through a signed endpoint on private buckets (MUL-5393) (#6088)

Bohan Jiang607209de7c7d
diff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.md
index 8792dfdde8..0e27f987eb 100644
--- a/SELF_HOSTING_ADVANCED.md
+++ b/SELF_HOSTING_ADVANCED.md
@@ -95,12 +95,35 @@ For file uploads and attachments, configure S3 and (optionally) CloudFront:
| `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` | Static credentials. When both are unset, the AWS SDK default credential chain is used |
| `AWS_ENDPOINT_URL` | Custom S3-compatible endpoint (e.g. MinIO, R2, B2). Setting this defaults to path-style URLs for backward compatibility |
| `S3_USE_PATH_STYLE` | Optional S3 addressing mode. Leave empty for the default (`true` when `AWS_ENDPOINT_URL` is set, `false` for AWS S3). Set `false` for S3-compatible providers that require virtual-hosted-style URLs |
-| `ATTACHMENT_DOWNLOAD_MODE` | Attachment download behavior: `auto` (default), `cloudfront`, `presign`, or `proxy`. Use `proxy` for private buckets behind Docker/VPC-only endpoints such as `http://rustfs:9000` |
+| `ATTACHMENT_DOWNLOAD_MODE` | Attachment download behavior: `auto` (default), `cloudfront`, `presign`, or `proxy`. Use `proxy` for private buckets behind Docker/VPC-only endpoints such as `http://rustfs:9000`. Avatars follow the same policy — see below |
| `ATTACHMENT_DOWNLOAD_URL_TTL` | TTL for CloudFront signed URLs and S3 presigned download URLs (default: `30m`) |
| `CLOUDFRONT_DOMAIN` | CloudFront distribution domain — when set, public URLs use this host instead of the S3 host |
| `CLOUDFRONT_KEY_PAIR_ID` | CloudFront key pair ID for signed URLs |
| `CLOUDFRONT_PRIVATE_KEY` | CloudFront private key (PEM format) |
+#### Avatars on a private bucket
+
+User / agent / squad / workspace avatars are stored as the raw storage object
+URL. When the bucket is public — a public `CLOUDFRONT_DOMAIN`, or the default
+local-disk backend — that URL is served to clients unchanged.
+
+When the bucket is private and no public CDN domain is configured (S3 with
+Block Public Access, R2, MinIO), the API instead serves avatars from
+`/api/avatars/<signature>/<key>` and resolves each request through
+`ATTACHMENT_DOWNLOAD_MODE` — a presigned redirect, a CloudFront-signed
+redirect, or a proxied body. The signature in the path is what authorizes the
+read: an auth-gated URL cannot be used as an `<img src>` from the Desktop app
+or a split-origin frontend, because the session cookie is `SameSite=Strict`.
+
+Only image objects resolve through this route, and only ones that are
+*avatar-class*: a standalone upload not attached to an issue, comment, chat, or
+task. Pointing an `avatar_url` at a file someone attached to an issue is
+rejected when it is set and 404s if it was already stored, so a private image
+cannot be turned into a public link by way of the avatar field.
+
+No configuration is required, and avatars uploaded before this behavior
+existed are fixed without a backfill.
+
### Cookies
| Variable | Description |
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 06b5a3a272..20941e6b37 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -759,6 +759,15 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// unchanged — this one is purely additive.
r.Get("/api/attachments/{id}/signed-download", h.DownloadAttachmentWithCapability)
+ // Avatar serving. Public for the same reason as the capability download
+ // above: the auth cookie is SameSite=Strict, so an auth-gated URL cannot
+ // be a native <img src> from Desktop / mobile webview or a split-origin
+ // self-hosted web app. The HMAC signature in the path is the credential.
+ // It covers the storage key, only image keys resolve, and the object must
+ // be avatar-class — see server/internal/handler/avatar.go (MUL-5393 /
+ // #6024).
+ r.Get("/api/avatars/{sig}/*", h.ServeAvatar)
+
// Auth (public) — per-IP rate limiting.
if rdb == nil {
slog.Warn("rate limiting disabled: REDIS_URL not configured")
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 008851f2f8..800a9e5d71 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -107,7 +107,7 @@ type AgentResponse struct {
// handler restores the persisted token instead of overwriting it.
const runtimeConfigGatewayTokenMask = "***"
-func agentToResponse(a db.Agent) AgentResponse {
+func (h *Handler) agentToResponse(a db.Agent) AgentResponse {
var rc any
if a.RuntimeConfig != nil {
json.Unmarshal(a.RuntimeConfig, &rc)
@@ -162,7 +162,7 @@ func agentToResponse(a db.Agent) AgentResponse {
Name: a.Name,
Description: a.Description,
Instructions: a.Instructions,
- AvatarURL: textToPtr(a.AvatarUrl),
+ AvatarURL: h.resolveAvatarURLPtr(textToPtr(a.AvatarUrl)),
RuntimeMode: a.RuntimeMode,
RuntimeConfig: rc,
CustomArgs: customArgs,
@@ -509,7 +509,7 @@ func (h *Handler) hydrateTaskAttributions(ctx context.Context, attrs []*TaskAttr
ref.Name = u.Name
ref.Email = u.Email
if u.AvatarUrl.Valid {
- ref.AvatarURL = u.AvatarUrl.String
+ ref.AvatarURL = h.resolveAvatarURL(u.AvatarUrl.String)
}
}
}
@@ -839,7 +839,7 @@ func (h *Handler) ListAgents(w http.ResponseWriter, r *http.Request) {
continue
}
}
- resp := agentToResponse(a)
+ resp := h.agentToResponse(a)
applyInvocationTargetsToResponse(&resp, targets)
if skills, ok := skillMap[resp.ID]; ok {
resp.Skills = skills
@@ -888,7 +888,7 @@ func (h *Handler) GetAgent(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusForbidden, "you do not have access to this agent")
return
}
- resp := agentToResponse(agent)
+ resp := h.agentToResponse(agent)
if !h.enrichAgentResponseWithTargetsHTTP(w, r, &resp, agent.ID) {
return
}
@@ -1136,6 +1136,11 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {
}
}
+ avatarURL, ok := h.newAgentAvatar(w, r, req.AvatarURL)
+ if !ok {
+ return
+ }
+
tx, err := h.TxStarter.Begin(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to start agent create transaction")
@@ -1149,7 +1154,7 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {
Name: req.Name,
Description: req.Description,
Instructions: req.Instructions,
- AvatarUrl: newAgentAvatar(req.AvatarURL),
+ AvatarUrl: avatarURL,
RuntimeMode: runtime.RuntimeMode,
RuntimeConfig: rc,
RuntimeID: runtime.ID,
@@ -1201,7 +1206,7 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {
created, _ = h.Queries.GetAgent(r.Context(), created.ID)
}
- resp := agentToResponse(created)
+ resp := h.agentToResponse(created)
if err := h.attachAgentSkills(r.Context(), &resp, created.ID); err != nil {
slog.Warn("create agent: load skills for response failed", append(logger.RequestAttrs(r), "error", err, "agent_id", uuidToString(created.ID))...)
}
@@ -1553,7 +1558,11 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {
params.Instructions = pgtype.Text{String: *req.Instructions, Valid: true}
}
if req.AvatarURL != nil {
- params.AvatarUrl = pgtype.Text{String: *req.AvatarURL, Valid: true}
+ avatarURL, ok := h.acceptAvatarURL(w, r, *req.AvatarURL, existing.AvatarUrl.String)
+ if !ok {
+ return
+ }
+ params.AvatarUrl = pgtype.Text{String: avatarURL, Valid: true}
}
if req.RuntimeConfig != nil {
// Restore the persisted gateway token when the request submitted the
@@ -1880,7 +1889,7 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {
}
}
- resp := agentToResponse(updated)
+ resp := h.agentToResponse(updated)
if err := h.enrichAgentResponseWithTargets(r.Context(), &resp, updated.ID); err != nil {
slog.Warn("update agent: load invocation targets for response failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)
writeError(w, http.StatusInternalServerError, "failed to load agent invocation targets")
@@ -1990,7 +1999,7 @@ func (h *Handler) ArchiveAgent(w http.ResponseWriter, r *http.Request) {
wsID := uuidToString(archived.WorkspaceID)
slog.Info("agent archived", append(logger.RequestAttrs(r), "agent_id", id, "workspace_id", wsID)...)
- resp := agentToResponse(archived)
+ resp := h.agentToResponse(archived)
if err := h.attachAgentSkills(r.Context(), &resp, archived.ID); err != nil {
slog.Warn("load agent skills after archive failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)
writeError(w, http.StatusInternalServerError, "failed to load agent skills")
@@ -2025,7 +2034,7 @@ func (h *Handler) RestoreAgent(w http.ResponseWriter, r *http.Request) {
wsID := uuidToString(restored.WorkspaceID)
slog.Info("agent restored", append(logger.RequestAttrs(r), "agent_id", id, "workspace_id", wsID)...)
- resp := agentToResponse(restored)
+ resp := h.agentToResponse(restored)
if err := h.attachAgentSkills(r.Context(), &resp, restored.ID); err != nil {
slog.Warn("load agent skills after restore failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)
writeError(w, http.StatusInternalServerError, "failed to load agent skills")
@@ -2248,7 +2257,7 @@ func (h *Handler) ListWorkspaceWorkingAgents(w http.ResponseWriter, r *http.Requ
resp = append(resp, WorkspaceWorkingAgent{
ID: agentID,
Name: row.Name,
- AvatarURL: textToPtr(row.AvatarUrl),
+ AvatarURL: h.resolveAvatarURLPtr(textToPtr(row.AvatarUrl)),
RunningTaskCount: row.RunningTaskCount,
IssueIDs: uuidStringsOrEmpty(row.IssueIds),
})
diff --git a/server/internal/handler/agent_avatar.go b/server/internal/handler/agent_avatar.go
index aba9c40644..c2421ebda6 100644
--- a/server/internal/handler/agent_avatar.go
+++ b/server/internal/handler/agent_avatar.go
@@ -3,6 +3,7 @@ package handler
import (
"crypto/rand"
"math/big"
+ "net/http"
"strings"
"github.com/jackc/pgx/v5/pgtype"
@@ -24,9 +25,18 @@ func randomAgentEmojiAvatar() string {
return agentEmojiAvatarPrefix + agentEmojiAvatars[index.Int64()]
}
-func newAgentAvatar(avatarURL *string) pgtype.Text {
+// newAgentAvatar resolves the avatar to persist for a newly created agent. An
+// explicit value is validated through acceptAvatarURL — a create path is still
+// a way to publish a storage object, so it carries the same authorization
+// boundary as an update. ok=false means the error response is already written
+// and the caller must abort.
+func (h *Handler) newAgentAvatar(w http.ResponseWriter, r *http.Request, avatarURL *string) (pgtype.Text, bool) {
if avatarURL != nil && strings.TrimSpace(*avatarURL) != "" {
- return pgtype.Text{String: *avatarURL, Valid: true}
+ accepted, ok := h.acceptAvatarURL(w, r, *avatarURL, "")
+ if !ok {
+ return pgtype.Text{}, false
+ }
+ return pgtype.Text{String: accepted, Valid: true}, true
}
- return pgtype.Text{String: randomAgentEmojiAvatar(), Valid: true}
+ return pgtype.Text{String: randomAgentEmojiAvatar(), Valid: true}, true
}
diff --git a/server/internal/handler/agent_env.go b/server/internal/handler/agent_env.go
index 90cc6f5300..122652b5ab 100644
--- a/server/internal/handler/agent_env.go
+++ b/server/internal/handler/agent_env.go
@@ -264,7 +264,7 @@ func (h *Handler) UpdateAgentEnv(w http.ResponseWriter, r *http.Request) {
// "N variables configured" indicator. Payload is the redacted
// AgentResponse — no env values are sent. Skills are reloaded so the
// broadcast doesn't tell subscribers the agent has no skills (#3459).
- resp := agentToResponse(updated)
+ resp := h.agentToResponse(updated)
if err := h.attachAgentSkills(r.Context(), &resp, updated.ID); err != nil {
slog.Warn("load agent skills after env update failed",
append(logger.RequestAttrs(r), "error", err, "agent_id", uuidToString(updated.ID))...)
diff --git a/server/internal/handler/agent_runtime_skills.go b/server/internal/handler/agent_runtime_skills.go
index 2274d3af0d..06aaa6d767 100644
--- a/server/internal/handler/agent_runtime_skills.go
+++ b/server/internal/handler/agent_runtime_skills.go
@@ -190,7 +190,7 @@ func (h *Handler) SetAgentRuntimeSkillEnabled(w http.ResponseWriter, r *http.Req
// "agent:status" event to invalidate workspaceKeys.agents. Without this only
// the initiating tab refreshes and other clients keep showing stale toggles.
locked.DisabledRuntimeSkills = payload
- resp := agentToResponse(locked)
+ resp := h.agentToResponse(locked)
if err := h.enrichAgentResponseWithTargets(r.Context(), &resp, locked.ID); err != nil {
slog.Warn("runtime skill toggle: load invocation targets for broadcast failed",
append(logger.RequestAttrs(r), "error", err, "agent_id", agentID)...)
diff --git a/server/internal/handler/agent_template.go b/server/internal/handler/agent_template.go
index 9c5e49bd3d..42a1f3317c 100644
--- a/server/internal/handler/agent_template.go
+++ b/server/internal/handler/agent_template.go
@@ -456,7 +456,10 @@ func (h *Handler) CreateAgentFromTemplate(w http.ResponseWriter, r *http.Request
if req.Instructions != nil {
instructions = *req.Instructions
}
- avatarURL := newAgentAvatar(req.AvatarURL)
+ avatarURL, ok := h.newAgentAvatar(w, r, req.AvatarURL)
+ if !ok {
+ return
+ }
agent, err := qtx.CreateAgent(r.Context(), db.CreateAgentParams{
WorkspaceID: wsUUID,
@@ -585,7 +588,7 @@ func (h *Handler) CreateAgentFromTemplate(w http.ResponseWriter, r *http.Request
agent, _ = h.Queries.GetAgent(r.Context(), agent.ID)
}
- resp := agentToResponse(agent)
+ resp := h.agentToResponse(agent)
// Templates attach skills via AddAgentSkill above, so the freshly built
// AgentResponse must reload them — otherwise the create response (and
// the agent:created broadcast) would tell clients the agent has no
diff --git a/server/internal/handler/auth.go b/server/internal/handler/auth.go
index 45cb3a6120..585a17b68f 100644
--- a/server/internal/handler/auth.go
+++ b/server/internal/handler/auth.go
@@ -73,7 +73,7 @@ type UserResponse struct {
// doesn't move the needle on prompt cost.
const MaxProfileDescriptionLen = 2000
-func userToResponse(u db.User) UserResponse {
+func (h *Handler) userToResponse(u db.User) UserResponse {
// JSONB column is []byte with DEFAULT '{}', so it's never nil at the DB
// level. Defensive coalesce just in case a future ALTER makes the column
// nullable and some row comes back with no default applied.
@@ -85,7 +85,7 @@ func userToResponse(u db.User) UserResponse {
ID: uuidToString(u.ID),
Name: u.Name,
Email: u.Email,
- AvatarURL: textToPtr(u.AvatarUrl),
+ AvatarURL: h.resolveAvatarURLPtr(textToPtr(u.AvatarUrl)),
Language: textToPtr(u.Language),
Timezone: textToPtr(u.Timezone),
OnboardedAt: timestampToPtr(u.OnboardedAt),
@@ -416,7 +416,7 @@ func (h *Handler) VerifyCode(w http.ResponseWriter, r *http.Request) {
slog.Info("user logged in", append(logger.RequestAttrs(r), "user_id", uuidToString(user.ID), "email", user.Email)...)
writeJSON(w, http.StatusOK, LoginResponse{
Token: tokenString,
- User: userToResponse(user),
+ User: h.userToResponse(user),
})
}
@@ -432,7 +432,7 @@ func (h *Handler) GetMe(w http.ResponseWriter, r *http.Request) {
return
}
- writeJSON(w, http.StatusOK, userToResponse(user))
+ writeJSON(w, http.StatusOK, h.userToResponse(user))
}
type UpdateMeRequest struct {
@@ -610,7 +610,7 @@ func (h *Handler) GoogleLogin(w http.ResponseWriter, r *http.Request) {
slog.Info("user logged in via google", append(logger.RequestAttrs(r), "user_id", uuidToString(user.ID), "email", user.Email)...)
writeJSON(w, http.StatusOK, LoginResponse{
Token: tokenString,
- User: userToResponse(user),
+ User: h.userToResponse(user),
})
}
@@ -676,7 +676,11 @@ func (h *Handler) UpdateMe(w http.ResponseWriter, r *http.Request) {
Name: name,
}
if req.AvatarURL != nil {
- params.AvatarUrl = pgtype.Text{String: strings.TrimSpace(*req.AvatarURL), Valid: true}
+ avatarURL, ok := h.acceptAvatarURL(w, r, *req.AvatarURL, currentUser.AvatarUrl.String)
+ if !ok {
+ return
+ }
+ params.AvatarUrl = pgtype.Text{String: avatarURL, Valid: true}
}
if req.Language != nil {
lang := strings.TrimSpace(*req.Language)
@@ -718,5 +722,5 @@ func (h *Handler) UpdateMe(w http.ResponseWriter, r *http.Request) {
return
}
- writeJSON(w, http.StatusOK, userToResponse(updatedUser))
+ writeJSON(w, http.StatusOK, h.userToResponse(updatedUser))
}
diff --git a/server/internal/handler/avatar.go b/server/internal/handler/avatar.go
new file mode 100644
index 0000000000..5b9330cb75
--- /dev/null
+++ b/server/internal/handler/avatar.go
@@ -0,0 +1,497 @@
+package handler
+
+import (
+ "context"
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/base64"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/url"
+ "path"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/auth"
+ "github.com/multica-ai/multica/server/internal/storage"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// ---------------------------------------------------------------------------
+// Avatar URLs (MUL-5393 / #6024)
+// ---------------------------------------------------------------------------
+//
+// `avatar_url` columns (user / agent / squad / workspace) store the raw
+// storage object URL the upload returned. On a deployment whose bucket is
+// public — S3/R2 behind a public CDN domain, or the LocalStorage backend
+// whose /uploads/* route is served publicly — that URL loads fine in an
+// <img> and nothing here changes it.
+//
+// On a PRIVATE bucket with no public CDN (S3 with Block Public Access, R2,
+// MinIO — the shape #6024 reports) that raw URL is a guaranteed 403 in the
+// browser: `ATTACHMENT_DOWNLOAD_MODE` only ever applied to the attachment
+// download endpoint, and avatars never went through it. Every avatar in the
+// deployment renders broken even though the upload itself succeeded.
+//
+// The fix resolves at READ time rather than at upload time:
+//
+// - What is PERSISTED stays the durable object reference (the raw storage
+// URL). Nothing with a TTL is ever written to the database — that is the
+// MUL-3130 regression this deliberately avoids — and avatars already
+// saved by an older build are fixed without a backfill.
+// - What is SERVED is `/api/avatars/<sig>/<key>`, a stable URL this server
+// resolves per request into a presigned redirect (or a proxied body)
+// using the deployment's existing storage download policy.
+//
+// The endpoint is unauthenticated on purpose, and the signature is the
+// credential. An auth-gated URL cannot be a native <img src>: the auth cookie
+// is SameSite=Strict, so a Desktop/mobile webview (token auth, non-API
+// document origin) and any split-origin self-hosted web app would fail the
+// resource load. This is the same reasoning behind CloudFront signed URLs,
+// and it is strictly tighter than the LocalStorage backend's existing
+// posture, where /uploads/* serves objects by key with no auth at all.
+//
+// Three things bound what a signed avatar URL can reach:
+//
+// - the HMAC covers the storage key, so a caller cannot mint one for a key
+// the server never published as an avatar;
+// - only image extensions resolve at all (see avatarContentType);
+// - and the object must be AVATAR-CLASS — a standalone image upload that is
+// not attached to an issue, comment, chat session, chat message, or task
+// (see avatarKeyIsPublishable).
+//
+// That last rule is the authorization boundary, and it is enforced on BOTH
+// sides. Being able to name a storage object is not permission to publish it:
+// without the check, any caller who had seen a private image attachment's raw
+// URL could submit it as their own avatar and the unauthenticated endpoint
+// would then keep re-signing it forever — and a user avatar propagates to
+// every workspace that user belongs to. The write side rejects such a value up
+// front; the read side re-checks per request, which is what makes the
+// guarantee hold for rows written before this check existed and revokes the
+// URL if an object is ever bound to a comment or chat afterwards.
+//
+// Uploader identity is deliberately NOT part of the rule. Duplicating an agent
+// legitimately reuses the source agent's avatar object, which a different
+// admin may have uploaded. The remaining theoretical case — publishing someone
+// else's *unbound* image — requires knowing that object's URL, and unbound
+// rows appear in no listing endpoint (ListAttachments is by issue,
+// groupAttachments by comment, chat attachments by message), so the only party
+// who ever sees one is its own uploader.
+
+const avatarURLPathPrefix = "/api/avatars/"
+
+// workspaceUploadNamespace is the storage prefix under which workspace-scoped
+// content lives — issue/comment/chat attachments, avatars, and channel media
+// ingest alike (see UploadFile and lark's mediaObjectKey). It is the only
+// namespace where an object can belong to somebody other than whoever is
+// setting the avatar, so it is the only one that has to prove itself.
+const workspaceUploadNamespace = "workspaces/"
+
+// avatarRedirectMaxAgeCap caps how long a client may reuse the 302 to a signed
+// storage URL. The effective value is also clamped against
+// attachmentDownloadURLTTL by avatarRedirectMaxAge so a cached redirect can
+// never outlive the signature it points at, however short the operator sets
+// the TTL.
+const avatarRedirectMaxAgeCap = 60
+
+// avatarProxyMaxAge is the cache lifetime for a proxied avatar body. Avatars
+// are immutable per key (every upload mints a fresh UUIDv7 key), so this is
+// only bounded by how quickly a re-upload should win.
+const avatarProxyMaxAge = 300
+
+// avatarExtContentTypes is the allowlist of avatar object types.
+//
+// SVG is deliberately absent. In proxy mode the body is served from the API
+// origin, and an inline image/svg+xml document is a script-execution vector
+// on navigation — the attachment proxy avoids it by forcing a download
+// disposition, which an avatar cannot do and still render. An SVG avatar
+// keeps its existing (pre-fix) behavior: the raw storage URL, which works on
+// every public-bucket deployment.
+var avatarExtContentTypes = map[string]string{
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".gif": "image/gif",
+ ".webp": "image/webp",
+ ".avif": "image/avif",
+ ".bmp": "image/bmp",
+ ".ico": "image/x-icon",
+}
+
+var (
+ avatarSigningKeyOnce sync.Once
+ avatarSigningKey []byte
+)
+
+// avatarURLSigningKey derives an avatar-specific HMAC key from JWT_SECRET via
+// SHA-256, so this signing domain never shares an identical key with session
+// tokens. Mirrors composioStateSecret in the router.
+func avatarURLSigningKey() []byte {
+ avatarSigningKeyOnce.Do(func() {
+ sum := sha256.Sum256(append([]byte("avatar-url:"), auth.JWTSecret()...))
+ avatarSigningKey = sum[:]
+ })
+ return avatarSigningKey
+}
+
+func signAvatarKey(key string) string {
+ mac := hmac.New(sha256.New, avatarURLSigningKey())
+ mac.Write([]byte(key))
+ return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
+}
+
+func avatarKeySignatureValid(key, sig string) bool {
+ return hmac.Equal([]byte(sig), []byte(signAvatarKey(key)))
+}
+
+// avatarContentType returns the Content-Type for an avatar storage key, or ""
+// when the key is not an allowed image. Extension-based on purpose: the key is
+// all this endpoint has, and it must decide before touching storage.
+func avatarContentType(key string) string {
+ return avatarExtContentTypes[strings.ToLower(path.Ext(key))]
+}
+
+// avatarURLPath builds the site-relative served URL for a storage key.
+func avatarURLPath(key string) string {
+ return avatarURLPathPrefix + signAvatarKey(key) + "/" + key
+}
+
+// avatarKeyFromServedURL recovers the storage key from a URL this server
+// previously emitted, verifying the signature. Accepts both the site-relative
+// and the PublicURL-absolute shape, because a client that round-trips a
+// resolved response back into avatar_url can persist either.
+func avatarKeyFromServedURL(raw string) (string, bool) {
+ rest := raw
+ if !strings.HasPrefix(rest, "/") {
+ u, err := url.Parse(raw)
+ if err != nil {
+ return "", false
+ }
+ rest = u.Path
+ }
+ rest, ok := strings.CutPrefix(rest, avatarURLPathPrefix)
+ if !ok {
+ return "", false
+ }
+ sig, key, ok := strings.Cut(rest, "/")
+ if !ok || key == "" {
+ return "", false
+ }
+ if !avatarKeySignatureValid(key, sig) {
+ return "", false
+ }
+ return key, true
+}
+
+// resolveAvatarURL turns a stored avatar_url into a URL a browser can load.
+//
+// Passthrough (the common case — the value is returned untouched) when it is
+// not one of our storage objects at all (an emoji marker, a data: URI, a
+// Google/GitHub profile URL), when it is not an allowed image type, or when
+// the deployment already serves the object publicly.
+func (h *Handler) resolveAvatarURL(raw string) string {
+ if raw == "" || h.Storage == nil {
+ return raw
+ }
+ // Already one of ours (a client round-tripped a resolved response back
+ // into avatar_url). Re-emit rather than nesting a second prefix; the
+ // signature check keeps this from being a way to get an arbitrary key
+ // signed.
+ if key, ok := avatarKeyFromServedURL(raw); ok {
+ return h.absolutizeAvatarPath(avatarURLPath(key))
+ }
+ key := h.ownedStorageKey(raw)
+ if key == "" || avatarContentType(key) == "" {
+ return raw
+ }
+ if h.avatarObjectLoadsUnauthenticated(raw) {
+ return raw
+ }
+ return h.absolutizeAvatarPath(avatarURLPath(key))
+}
+
+// resolveAvatarURLPtr is resolveAvatarURL over the *string shape the response
+// DTOs use. Nil and empty stay as they are so "no avatar" keeps its meaning.
+func (h *Handler) resolveAvatarURLPtr(raw *string) *string {
+ if raw == nil || *raw == "" {
+ return raw
+ }
+ resolved := h.resolveAvatarURL(*raw)
+ if resolved == *raw {
+ return raw
+ }
+ return &resolved
+}
+
+// normalizeStoredAvatarURL is the write-side inverse: a client that PATCHes
+// back a resolved `/api/avatars/...` value gets the durable object reference
+// stored instead. Keeps the column's invariant — avatar_url holds a storage
+// object URL — so a JWT_SECRET rotation can never strand an avatar behind a
+// signature the server no longer accepts.
+func (h *Handler) normalizeStoredAvatarURL(raw string) string {
+ if h.Storage == nil {
+ return raw
+ }
+ if key, ok := avatarKeyFromServedURL(raw); ok {
+ return h.Storage.ObjectURL(key)
+ }
+ return raw
+}
+
+// acceptAvatarURL validates a client-supplied avatar_url and returns the value
+// to persist. It writes the error response and returns ok=false when the
+// caller must abort — same shape as loadIssueForUser and friends.
+//
+// `current` is the entity's stored avatar_url. An unchanged re-send is
+// accepted without re-validation: clients round-trip whole objects, and a
+// value that is already persisted grants nothing new.
+func (h *Handler) acceptAvatarURL(w http.ResponseWriter, r *http.Request, raw, current string) (string, bool) {
+ value := h.normalizeStoredAvatarURL(strings.TrimSpace(raw))
+ if h.Storage == nil || value == strings.TrimSpace(current) {
+ return value, true
+ }
+ // Not one of our storage objects (emoji marker, data: URI, third-party
+ // profile URL) — nothing to authorize, and nothing this endpoint will
+ // ever sign.
+ key := h.ownedStorageKey(value)
+ if key == "" {
+ return value, true
+ }
+ if !h.avatarKeyIsPublishable(r.Context(), key) {
+ writeError(w, http.StatusForbidden, "avatar_url must reference a standalone image upload, not a file attached to an issue, comment, or chat")
+ return "", false
+ }
+ return value, true
+}
+
+// avatarKeyIsPublishable reports whether a storage object may be served
+// through the public avatar endpoint. See the file header for why this is the
+// authorization boundary rather than a mere sanity check.
+//
+// The key's basename is the attachment id: UploadFile mints one UUIDv7 and
+// uses it as both the row id and the object filename, so this resolves the
+// backing row without a lookup by URL (and without an index on it).
+func (h *Handler) avatarKeyIsPublishable(ctx context.Context, key string) bool {
+ if avatarContentType(key) == "" {
+ return false
+ }
+ if !strings.HasPrefix(key, workspaceUploadNamespace) {
+ // Outside the workspace namespace nothing can hold another user's
+ // content: UploadFile only ever writes `workspaces/…` or
+ // `users/<uploader>/…`, and the per-user branch creates no bindings.
+ // Any other prefix is an object the operator put in the bucket
+ // themselves, which they are entitled to point an avatar at.
+ return true
+ }
+ attID, ok := attachmentIDFromStorageKey(key)
+ if !ok {
+ // Inside the workspace namespace but not an upload row — channel
+ // media ingest writes `workspaces/<ws>/lark/…` keys here too. Fail
+ // closed.
+ return false
+ }
+ att, err := h.Queries.GetAttachmentByIDOnly(ctx, attID)
+ if err != nil {
+ return false
+ }
+ if !strings.HasPrefix(strings.ToLower(att.ContentType), "image/") {
+ return false
+ }
+ return !attachmentIsBound(att)
+}
+
+// attachmentIsBound reports whether an upload is attached to workspace content.
+// A bound row is somebody's issue/comment/chat file — never an avatar.
+func attachmentIsBound(att db.Attachment) bool {
+ return att.IssueID.Valid ||
+ att.CommentID.Valid ||
+ att.ChatSessionID.Valid ||
+ att.ChatMessageID.Valid ||
+ att.TaskID.Valid
+}
+
+// attachmentIDFromStorageKey recovers the attachment id UploadFile embedded in
+// the object filename (`<prefix>/<uuid><ext>`).
+func attachmentIDFromStorageKey(key string) (pgtype.UUID, bool) {
+ base := path.Base(key)
+ stem := strings.TrimSuffix(base, path.Ext(base))
+ id, err := util.ParseUUID(stem)
+ if err != nil {
+ return pgtype.UUID{}, false
+ }
+ return id, true
+}
+
+// ownedStorageKey returns the storage key for rawURL when — and only when —
+// this deployment's storage backend is what produced that URL.
+//
+// The round-trip through ObjectURL is what makes this safe: KeyFromURL is
+// lossy by design (it falls back to "everything after the last slash" for
+// unrecognized inputs), so a Google or GitHub avatar URL would otherwise
+// yield a plausible-looking key. Re-deriving the URL from the key and
+// requiring an exact match rejects anything this storage did not mint.
+func (h *Handler) ownedStorageKey(rawURL string) string {
+ key := h.Storage.KeyFromURL(rawURL)
+ if key == "" || key == rawURL {
+ return ""
+ }
+ if h.Storage.ObjectURL(key) != rawURL {
+ return ""
+ }
+ return key
+}
+
+// avatarObjectLoadsUnauthenticated reports whether the raw storage URL is
+// already loadable by an unauthenticated browser fetch, in which case
+// rewriting it would only add a pointless hop through the API.
+func (h *Handler) avatarObjectLoadsUnauthenticated(rawURL string) bool {
+ // LocalStorage objects are served by the public /uploads/* route, whether
+ // the stored URL is site-relative or absolute via LOCAL_UPLOAD_BASE_URL.
+ if _, ok := h.Storage.(*storage.LocalStorage); ok {
+ return true
+ }
+ // Otherwise: a public CDN domain with no per-request CloudFront signing.
+ // In signed-CloudFront mode the same domain serves private content and the
+ // unsigned URL is a 403, so that shape resolves through the endpoint too.
+ return h.storageURLIsPubliclyReadable(rawURL)
+}
+
+// absolutizeAvatarPath anchors the served path on MULTICA_PUBLIC_URL when it
+// is configured, so clients that don't share the API's document origin
+// (Desktop, mobile webview) can load it. Same policy as buildMarkdownURL;
+// falling back to the site-relative path is safe because every client
+// resolves avatar URLs through resolvePublicFileUrl, which prefixes its API
+// base URL.
+func (h *Handler) absolutizeAvatarPath(relPath string) string {
+ if publicURL := strings.TrimRight(h.cfg.PublicURL, "/"); publicURL != "" {
+ return publicURL + relPath
+ }
+ return relPath
+}
+
+// ---------------------------------------------------------------------------
+// ServeAvatar — GET /api/avatars/{sig}/*
+// ---------------------------------------------------------------------------
+//
+// Unauthenticated by design (the signature is the credential) — see the file
+// header. Resolution reuses resolveAttachmentDownloadMode so an avatar and an
+// attachment obey the same ATTACHMENT_DOWNLOAD_MODE policy on a given
+// deployment; there is one storage backend and one right way to read from it.
+func (h *Handler) ServeAvatar(w http.ResponseWriter, r *http.Request) {
+ if h.Storage == nil {
+ http.NotFound(w, r)
+ return
+ }
+
+ key, err := url.PathUnescape(chi.URLParam(r, "*"))
+ if err != nil || key == "" {
+ http.NotFound(w, r)
+ return
+ }
+ contentType := avatarContentType(key)
+ // Deny shape is a flat 404 for a bad signature, an unknown key, a
+ // non-image key, and an object that is not avatar-class alike, so the
+ // route is not an oracle for any of them. The publishable check runs on
+ // every request rather than only at write time: it is what bounds rows
+ // written before the write-side gate existed, and it revokes the URL if
+ // the object is later bound to a comment or chat.
+ if contentType == "" ||
+ !avatarKeySignatureValid(key, chi.URLParam(r, "sig")) ||
+ !h.avatarKeyIsPublishable(r.Context(), key) {
+ http.NotFound(w, r)
+ return
+ }
+
+ objectURL := h.Storage.ObjectURL(key)
+ h.setAttachmentPreviewSecurityHeaders(w)
+
+ switch h.resolveAttachmentDownloadMode(objectURL) {
+ case attachmentDownloadModeCloudFront:
+ if h.CFSigner == nil {
+ writeError(w, http.StatusInternalServerError, "cloudfront avatar downloads are not configured")
+ return
+ }
+ setAvatarCacheControl(w, h.avatarRedirectMaxAge())
+ http.Redirect(w, r, h.CFSigner.SignedURL(objectURL, time.Now().Add(h.attachmentDownloadURLTTL())), http.StatusFound)
+ case attachmentDownloadModePresign:
+ presigner, ok := h.Storage.(storage.DownloadPresigner)
+ if !ok {
+ writeError(w, http.StatusInternalServerError, "avatar storage does not support presigned downloads")
+ return
+ }
+ // Empty disposition inherits the object's stored Content-Disposition
+ // (inline for images), which is what keeps the redirect renderable in
+ // an <img> instead of triggering a download.
+ signedURL, err := presigner.PresignGetWithContentDisposition(r.Context(), key, h.attachmentDownloadURLTTL(), "")
+ if err != nil {
+ slog.Error("failed to presign avatar", "key", key, "error", err)
+ writeError(w, http.StatusBadGateway, "failed to create avatar URL")
+ return
+ }
+ setAvatarCacheControl(w, h.avatarRedirectMaxAge())
+ http.Redirect(w, r, signedURL, http.StatusFound)
+ case attachmentDownloadModeProxy:
+ h.proxyAvatar(w, r, key, contentType)
+ default:
+ writeError(w, http.StatusInternalServerError, "invalid attachment download mode")
+ }
+}
+
+// proxyAvatar streams the object through the API for backends that cannot be
+// reached directly by the browser (local disk, or a private host such as
+// http://rustfs:9000). No Range handling: avatars are small images loaded by
+// <img>, not resumable downloads.
+func (h *Handler) proxyAvatar(w http.ResponseWriter, r *http.Request, key, contentType string) {
+ reader, err := h.Storage.GetReader(r.Context(), key)
+ if err != nil {
+ slog.Warn("avatar object not found", "key", key, "error", err)
+ http.NotFound(w, r)
+ return
+ }
+ defer reader.Close()
+
+ w.Header().Set("Content-Type", contentType)
+ w.Header().Set("Content-Disposition", "inline")
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ setAvatarCacheControl(w, avatarProxyMaxAge)
+
+ if _, err := io.Copy(w, reader); err != nil {
+ slog.Warn("avatar stream interrupted", "key", key, "error", err)
+ }
+}
+
+// avatarRedirectMaxAge is how long a client may reuse the 302, clamped to half
+// the signed URL's own lifetime. ATTACHMENT_DOWNLOAD_URL_TTL accepts any
+// positive duration, so a fixed 60s would let a browser or proxy keep replaying
+// a redirect to an already-expired storage URL on a deployment that configures
+// a shorter TTL. Returns 0 (no caching at all) when the TTL is too short for
+// any margin to be safe.
+func (h *Handler) avatarRedirectMaxAge() int {
+ ttlSeconds := int(h.attachmentDownloadURLTTL() / time.Second)
+ maxAge := ttlSeconds / 2
+ if maxAge > avatarRedirectMaxAgeCap {
+ return avatarRedirectMaxAgeCap
+ }
+ if maxAge < 0 {
+ return 0
+ }
+ return maxAge
+}
+
+// setAvatarCacheControl marks the response private: the URL is unguessable
+// but it is still a per-deployment identity image, and a shared proxy has no
+// business holding a copy. A zero max-age means "do not store at all" rather
+// than "store for zero seconds", which some intermediaries round up.
+func setAvatarCacheControl(w http.ResponseWriter, maxAge int) {
+ if maxAge <= 0 {
+ w.Header().Set("Cache-Control", "no-store")
+ return
+ }
+ w.Header().Set("Cache-Control", "private, max-age="+strconv.Itoa(maxAge))
+}
diff --git a/server/internal/handler/avatar_test.go b/server/internal/handler/avatar_test.go
new file mode 100644
index 0000000000..883329b504
--- /dev/null
+++ b/server/internal/handler/avatar_test.go
@@ -0,0 +1,588 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/storage"
+)
+
+// withAvatarStorage swaps the handler's storage/config for one test and
+// restores it afterwards. Mirrors the setup the attachment download tests use.
+func withAvatarStorage(t *testing.T, store storage.Storage, publicURL string) {
+ t.Helper()
+ origStorage := testHandler.Storage
+ origCfg := testHandler.cfg
+ origSigner := testHandler.CFSigner
+ testHandler.Storage = store
+ testHandler.cfg.PublicURL = publicURL
+ testHandler.cfg.AttachmentDownloadMode = "auto"
+ testHandler.CFSigner = nil
+ t.Cleanup(func() {
+ testHandler.Storage = origStorage
+ testHandler.cfg = origCfg
+ testHandler.CFSigner = origSigner
+ })
+}
+
+const testAvatarKey = "workspaces/11111111-1111-1111-1111-111111111111/avatar.png"
+
+// TestResolveAvatarURL_PrivateStorageRewritesToSignedEndpoint is the #6024
+// case: a private bucket with no public CDN stored a raw S3 URL in avatar_url,
+// which the browser can only 403 on. Reads must hand back the signed avatar
+// endpoint instead.
+func TestResolveAvatarURL_PrivateStorageRewritesToSignedEndpoint(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+
+ raw := "https://cdn.example.com/" + testAvatarKey
+ got := testHandler.resolveAvatarURL(raw)
+
+ want := avatarURLPathPrefix + signAvatarKey(testAvatarKey) + "/" + testAvatarKey
+ if got != want {
+ t.Fatalf("resolveAvatarURL = %q, want %q", got, want)
+ }
+ key, ok := avatarKeyFromServedURL(got)
+ if !ok || key != testAvatarKey {
+ t.Fatalf("resolved URL does not verify back to the key: key=%q ok=%v", key, ok)
+ }
+}
+
+// TestResolveAvatarURL_PublicCdnUnchanged guards the deployments that already
+// work: a public CDN domain with no per-request signing serves the raw URL
+// fine, and routing it through the API would only add a hop.
+func TestResolveAvatarURL_PublicCdnUnchanged(t *testing.T) {
+ withAvatarStorage(t, &mockStorage{}, "")
+
+ raw := "https://cdn.example.com/" + testAvatarKey
+ if got := testHandler.resolveAvatarURL(raw); got != raw {
+ t.Fatalf("resolveAvatarURL = %q, want unchanged %q", got, raw)
+ }
+}
+
+// TestResolveAvatarURL_CloudFrontSignedRewrites covers the other private
+// shape: a CDN domain IS configured, but it serves private content through
+// per-request signed URLs, so the unsigned stored URL is a 403.
+func TestResolveAvatarURL_CloudFrontSignedRewrites(t *testing.T) {
+ withAvatarStorage(t, &mockStorage{}, "")
+ testHandler.CFSigner = testCloudFrontSigner(t)
+
+ raw := "https://cdn.example.com/" + testAvatarKey
+ if got := testHandler.resolveAvatarURL(raw); !strings.HasPrefix(got, avatarURLPathPrefix) {
+ t.Fatalf("resolveAvatarURL = %q, want the signed avatar endpoint", got)
+ }
+}
+
+// TestResolveAvatarURL_LocalStorageUnchanged — LocalStorage objects are served
+// by the public /uploads/* route, so they are already loadable as-is.
+func TestResolveAvatarURL_LocalStorageUnchanged(t *testing.T) {
+ local := storage.NewLocalStorageFromEnv()
+ if local == nil {
+ t.Skip("local storage unavailable")
+ }
+ withAvatarStorage(t, local, "")
+
+ raw := local.ObjectURL(testAvatarKey)
+ if got := testHandler.resolveAvatarURL(raw); got != raw {
+ t.Fatalf("resolveAvatarURL = %q, want unchanged %q", got, raw)
+ }
+}
+
+// TestResolveAvatarURL_PassesThroughForeignValues — avatar_url also holds
+// emoji markers, inline data URIs, and third-party profile URLs. None of them
+// are our storage objects and all must survive untouched.
+func TestResolveAvatarURL_PassesThroughForeignValues(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+
+ for _, raw := range []string{
+ "",
+ "emoji:🐙",
+ "data:image/svg+xml,%3Csvg%3E%3C/svg%3E",
+ "https://lh3.googleusercontent.com/a/profile.png",
+ "https://avatars.githubusercontent.com/u/12345?v=4",
+ } {
+ if got := testHandler.resolveAvatarURL(raw); got != raw {
+ t.Errorf("resolveAvatarURL(%q) = %q, want unchanged", raw, got)
+ }
+ }
+}
+
+// TestResolveAvatarURL_NonImageKeyUnchanged — an avatar_url pointed at a
+// non-image object must not be laundered into a publicly fetchable URL.
+func TestResolveAvatarURL_NonImageKeyUnchanged(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+
+ for _, key := range []string{"workspaces/ws/secret.pdf", "workspaces/ws/logo.svg", "workspaces/ws/noext"} {
+ raw := "https://cdn.example.com/" + key
+ if got := testHandler.resolveAvatarURL(raw); got != raw {
+ t.Errorf("resolveAvatarURL(%q) = %q, want unchanged", raw, got)
+ }
+ }
+}
+
+// TestResolveAvatarURL_AnchorsOnPublicURL — clients that don't share the API's
+// document origin (Desktop, mobile webview) need an absolute URL.
+func TestResolveAvatarURL_AnchorsOnPublicURL(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "https://api.example.test/")
+
+ got := testHandler.resolveAvatarURL("https://cdn.example.com/" + testAvatarKey)
+ if !strings.HasPrefix(got, "https://api.example.test"+avatarURLPathPrefix) {
+ t.Fatalf("resolveAvatarURL = %q, want it anchored on PublicURL", got)
+ }
+ key, ok := avatarKeyFromServedURL(got)
+ if !ok || key != testAvatarKey {
+ t.Fatalf("absolute URL does not verify back to the key: key=%q ok=%v", key, ok)
+ }
+}
+
+// TestResolveAvatarURL_RoundTripIsStable — a client may PATCH a resolved
+// response value straight back into avatar_url. Resolving it again must not
+// nest a second prefix.
+func TestResolveAvatarURL_RoundTripIsStable(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+
+ once := testHandler.resolveAvatarURL("https://cdn.example.com/" + testAvatarKey)
+ if twice := testHandler.resolveAvatarURL(once); twice != once {
+ t.Fatalf("resolveAvatarURL is not idempotent: %q then %q", once, twice)
+ }
+}
+
+// TestResolveAvatarURL_ForgedAvatarPathNotReSigned — an unsigned or
+// wrongly-signed avatar path must not be accepted and re-signed, or storing
+// one would be a way to publish an arbitrary object.
+func TestResolveAvatarURL_ForgedAvatarPathNotReSigned(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+
+ forged := avatarURLPathPrefix + "not-a-signature/" + testAvatarKey
+ if got := testHandler.resolveAvatarURL(forged); got != forged {
+ t.Fatalf("resolveAvatarURL(%q) = %q, want unchanged (no re-signing)", forged, got)
+ }
+}
+
+// TestNormalizeStoredAvatarURL_RecoversObjectURL — the write side keeps the
+// column holding a durable object reference even when a client sends back the
+// resolved value.
+func TestNormalizeStoredAvatarURL_RecoversObjectURL(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "https://api.example.test")
+
+ raw := "https://cdn.example.com/" + testAvatarKey
+ resolved := testHandler.resolveAvatarURL(raw)
+ if got := testHandler.normalizeStoredAvatarURL(resolved); got != raw {
+ t.Fatalf("normalizeStoredAvatarURL = %q, want the object URL %q", got, raw)
+ }
+ // Anything else is stored verbatim.
+ for _, other := range []string{raw, "emoji:🐙", "https://lh3.googleusercontent.com/a/p.png"} {
+ if got := testHandler.normalizeStoredAvatarURL(other); got != other {
+ t.Errorf("normalizeStoredAvatarURL(%q) = %q, want unchanged", other, got)
+ }
+ }
+}
+
+func serveAvatarRequest(t *testing.T, sig, key string) *httptest.ResponseRecorder {
+ t.Helper()
+ r := chi.NewRouter()
+ r.Get("/api/avatars/{sig}/*", testHandler.ServeAvatar)
+ req := httptest.NewRequest(http.MethodGet, "/api/avatars/"+sig+"/"+key, nil)
+ w := httptest.NewRecorder()
+ r.ServeHTTP(w, req)
+ return w
+}
+
+// avatarObjectOpts describes a seeded storage object the way UploadFile would
+// have written it: the attachment row's id IS the object filename.
+type avatarObjectOpts struct {
+ contentType string
+ // boundToIssue attaches the row to a real issue — the shape a private
+ // image attachment has, and the shape that must never become a public
+ // avatar.
+ boundToIssue bool
+ // foreignWorkspace seeds the object in a freshly created workspace the
+ // fixture user is not a member of.
+ foreignWorkspace bool
+}
+
+// seedForeignWorkspace creates a workspace the fixture user has no membership
+// in, for the cross-workspace leg of the authorization tests.
+func seedForeignWorkspace(t *testing.T) string {
+ t.Helper()
+ slug := "avatar-foreign-" + uuid.NewString()[:8]
+ var id string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO workspace (name, slug, description, issue_prefix)
+ VALUES ($1, $1, '', 'AVF')
+ RETURNING id::text
+ `, slug).Scan(&id); err != nil {
+ t.Fatalf("seed workspace: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, id)
+ })
+ return id
+}
+
+// seedIssueForAvatarTest creates an issue an attachment can hang off.
+func seedIssueForAvatarTest(t *testing.T, workspaceID string) string {
+ t.Helper()
+ var id string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO issue (workspace_id, title, status, priority, creator_type, creator_id, number)
+ VALUES ($1, 'avatar authorization fixture', 'todo', 'medium', 'member', $2,
+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))
+ RETURNING id::text
+ `, workspaceID, testUserID).Scan(&id); err != nil {
+ t.Fatalf("seed issue: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, id)
+ })
+ return id
+}
+
+// seedAvatarObject inserts the attachment row and returns its storage key.
+func seedAvatarObject(t *testing.T, opts avatarObjectOpts) string {
+ t.Helper()
+ id, err := uuid.NewV7()
+ if err != nil {
+ t.Fatalf("generate attachment id: %v", err)
+ }
+ if opts.contentType == "" {
+ opts.contentType = "image/png"
+ }
+ workspaceID := testWorkspaceID
+ if opts.foreignWorkspace {
+ workspaceID = seedForeignWorkspace(t)
+ }
+ var issueID any
+ if opts.boundToIssue {
+ issueID = seedIssueForAvatarTest(t, workspaceID)
+ }
+ key := "workspaces/" + workspaceID + "/" + id.String() + ".png"
+ if _, err := testPool.Exec(context.Background(), `
+ INSERT INTO attachment (id, workspace_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, issue_id)
+ VALUES ($1, $2, 'member', $3, 'avatar.png', $4, $5, 10, $6)
+ `, id.String(), workspaceID, testUserID,
+ "https://cdn.example.com/"+key, opts.contentType, issueID); err != nil {
+ t.Fatalf("seed attachment row: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM attachment WHERE id = $1`, id.String())
+ })
+ return key
+}
+
+// TestServeAvatar_PresignRedirects — the private-bucket read path: a valid
+// signature yields a 302 to a freshly presigned storage URL with no forced
+// download disposition, so it renders inside an <img>.
+func TestServeAvatar_PresignRedirects(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+ key := seedAvatarObject(t, avatarObjectOpts{})
+
+ w := serveAvatarRequest(t, signAvatarKey(key), key)
+ if w.Code != http.StatusFound {
+ t.Fatalf("status = %d, want 302; body=%s", w.Code, w.Body.String())
+ }
+ loc, err := url.Parse(w.Header().Get("Location"))
+ if err != nil {
+ t.Fatalf("parse Location: %v", err)
+ }
+ if loc.Query().Get("X-Amz-Signature") == "" {
+ t.Fatalf("Location = %q, want a presigned storage URL", loc.String())
+ }
+ if got := loc.Query().Get("response-content-disposition"); got != "" {
+ t.Fatalf("response-content-disposition = %q, want inline-loadable URL", got)
+ }
+}
+
+// TestServeAvatar_RejectsForgedSignature — the signature is the credential;
+// without it the endpoint must not reach storage at all.
+func TestServeAvatar_RejectsForgedSignature(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+ key := seedAvatarObject(t, avatarObjectOpts{})
+
+ for _, sig := range []string{"", "deadbeef", signAvatarKey("workspaces/other/x.png")} {
+ if w := serveAvatarRequest(t, sig, key); w.Code != http.StatusNotFound {
+ t.Errorf("sig %q: status = %d, want 404", sig, w.Code)
+ }
+ }
+}
+
+// TestServeAvatar_RejectsNonImageKey — a correctly signed non-image key still
+// 404s, so this route can never serve a document.
+func TestServeAvatar_RejectsNonImageKey(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+
+ key := "workspaces/ws/private.pdf"
+ if w := serveAvatarRequest(t, signAvatarKey(key), key); w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404", w.Code)
+ }
+}
+
+// TestServeAvatar_ProxiesPrivateHostBody — a bucket reachable only from inside
+// the network (http://rustfs:9000) can't be redirected to, so the body streams
+// through the API with an inline image content type.
+func TestServeAvatar_ProxiesPrivateHostBody(t *testing.T) {
+ store := &mockStorage{}
+ withAvatarStorage(t, store, "")
+ testHandler.cfg.AttachmentDownloadMode = "proxy"
+ key := seedAvatarObject(t, avatarObjectOpts{})
+ store.put(key, []byte("PNGBYTES"))
+
+ w := serveAvatarRequest(t, signAvatarKey(key), key)
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
+ }
+ if got := w.Header().Get("Content-Type"); got != "image/png" {
+ t.Fatalf("Content-Type = %q, want image/png", got)
+ }
+ if got := w.Header().Get("Content-Disposition"); got != "inline" {
+ t.Fatalf("Content-Disposition = %q, want inline", got)
+ }
+ if w.Body.String() != "PNGBYTES" {
+ t.Fatalf("body = %q, want the stored object", w.Body.String())
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Authorization boundary (MUL-5393 review)
+// ---------------------------------------------------------------------------
+//
+// Naming a storage object is not permission to publish it. These cover the
+// reproduced escalation: a private image attached to an issue must not become
+// a permanently public, unauthenticated avatar link — on the read side or the
+// write side, in this workspace or any other.
+
+// TestServeAvatar_RejectsAttachmentBoundToIssue is the reproduced attack. Even
+// with a valid signature (i.e. the value really did get stored in avatar_url),
+// an object attached to workspace content must never be served.
+func TestServeAvatar_RejectsAttachmentBoundToIssue(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+ key := seedAvatarObject(t, avatarObjectOpts{boundToIssue: true})
+
+ if w := serveAvatarRequest(t, signAvatarKey(key), key); w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404 for an issue attachment", w.Code)
+ }
+}
+
+// TestServeAvatar_RejectsForeignWorkspaceAttachment — the cross-workspace leg:
+// a private image from a workspace the avatar's owner has nothing to do with
+// is still an issue attachment, so it stays unreachable.
+func TestServeAvatar_RejectsForeignWorkspaceAttachment(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+ key := seedAvatarObject(t, avatarObjectOpts{foreignWorkspace: true, boundToIssue: true})
+
+ if w := serveAvatarRequest(t, signAvatarKey(key), key); w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404 for another workspace's attachment", w.Code)
+ }
+}
+
+// TestServeAvatar_RejectsNonImageAttachmentRow — the extension says image, the
+// row says otherwise. Fail closed on the row, which is the authoritative one.
+func TestServeAvatar_RejectsNonImageAttachmentRow(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+ key := seedAvatarObject(t, avatarObjectOpts{contentType: "application/pdf"})
+
+ if w := serveAvatarRequest(t, signAvatarKey(key), key); w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404 for a non-image row", w.Code)
+ }
+}
+
+// TestServeAvatar_RejectsWorkspaceKeyWithoutAttachmentRow — a workspace-scoped
+// key with no backing row can't be shown to be avatar-class, so it fails
+// closed rather than being served on the strength of its shape alone.
+func TestServeAvatar_RejectsWorkspaceKeyWithoutAttachmentRow(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+ key := "workspaces/" + testWorkspaceID + "/" + uuid.NewString() + ".png"
+
+ if w := serveAvatarRequest(t, signAvatarKey(key), key); w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404 for a key with no attachment row", w.Code)
+ }
+}
+
+// TestServeAvatar_AllowsUserNamespaceUpload — UploadFile's no-workspace branch
+// writes to users/<id>/ and creates no attachment row. That namespace never
+// holds issue/comment/chat content, so it stays serveable.
+func TestServeAvatar_AllowsUserNamespaceUpload(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+ key := "users/" + testUserID + "/" + uuid.NewString() + ".png"
+
+ if w := serveAvatarRequest(t, signAvatarKey(key), key); w.Code != http.StatusFound {
+ t.Fatalf("status = %d, want 302 for a standalone user upload", w.Code)
+ }
+}
+
+func acceptAvatarURL(t *testing.T, raw, current string) (string, int) {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodPatch, "/api/me", nil)
+ req.Header.Set("X-User-ID", testUserID)
+ req.Header.Set("X-Workspace-ID", testWorkspaceID)
+ w := httptest.NewRecorder()
+ value, ok := testHandler.acceptAvatarURL(w, req, raw, current)
+ if !ok {
+ return "", w.Code
+ }
+ return value, http.StatusOK
+}
+
+// TestAcceptAvatarURL_RejectsBoundAttachment — the write side refuses to store
+// the value at all, so the escalation is stopped before anything is persisted.
+func TestAcceptAvatarURL_RejectsBoundAttachment(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+ key := seedAvatarObject(t, avatarObjectOpts{boundToIssue: true})
+
+ _, status := acceptAvatarURL(t, "https://cdn.example.com/"+key, "")
+ if status != http.StatusForbidden {
+ t.Fatalf("status = %d, want 403 for an issue attachment", status)
+ }
+}
+
+// TestAcceptAvatarURL_AcceptsStandaloneUpload — the real avatar flow: an
+// unbound image upload is exactly what AvatarUploadControl produces.
+func TestAcceptAvatarURL_AcceptsStandaloneUpload(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+ key := seedAvatarObject(t, avatarObjectOpts{})
+
+ raw := "https://cdn.example.com/" + key
+ value, status := acceptAvatarURL(t, raw, "")
+ if status != http.StatusOK {
+ t.Fatalf("status = %d, want 200", status)
+ }
+ if value != raw {
+ t.Fatalf("stored value = %q, want the object URL %q", value, raw)
+ }
+}
+
+// TestAcceptAvatarURL_AcceptsUnchangedResend — clients round-trip whole
+// objects. Re-sending what is already persisted grants nothing new, so it must
+// not start failing after this gate landed (agent duplicate, profile form
+// resubmit).
+func TestAcceptAvatarURL_AcceptsUnchangedResend(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+ key := seedAvatarObject(t, avatarObjectOpts{boundToIssue: true})
+ raw := "https://cdn.example.com/" + key
+
+ if _, status := acceptAvatarURL(t, raw, raw); status != http.StatusOK {
+ t.Fatalf("status = %d, want 200 for an unchanged re-send", status)
+ }
+}
+
+// TestAcceptAvatarURL_NormalizesServedURL — a client that PATCHes back the
+// resolved response value stores the durable object reference, not the signed
+// path, so a JWT_SECRET rotation can't strand the avatar.
+func TestAcceptAvatarURL_NormalizesServedURL(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+ key := seedAvatarObject(t, avatarObjectOpts{})
+ raw := "https://cdn.example.com/" + key
+
+ value, status := acceptAvatarURL(t, testHandler.resolveAvatarURL(raw), "")
+ if status != http.StatusOK {
+ t.Fatalf("status = %d, want 200", status)
+ }
+ if value != raw {
+ t.Fatalf("stored value = %q, want the object URL %q", value, raw)
+ }
+}
+
+// TestAcceptAvatarURL_PassesThroughForeignValues — emoji markers, data URIs
+// and third-party profile URLs are not ours to authorize and must not 403.
+func TestAcceptAvatarURL_PassesThroughForeignValues(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+
+ for _, raw := range []string{
+ "",
+ "emoji:🐙",
+ "data:image/svg+xml,%3Csvg%3E%3C/svg%3E",
+ "https://lh3.googleusercontent.com/a/profile.png",
+ } {
+ value, status := acceptAvatarURL(t, raw, "")
+ if status != http.StatusOK {
+ t.Errorf("acceptAvatarURL(%q) status = %d, want 200", raw, status)
+ continue
+ }
+ if value != raw {
+ t.Errorf("acceptAvatarURL(%q) = %q, want unchanged", raw, value)
+ }
+ }
+}
+
+// TestAvatarRedirectMaxAge_StaysBelowSignatureTTL — ATTACHMENT_DOWNLOAD_URL_TTL
+// takes any positive duration. A fixed 60s cache would let a browser replay a
+// redirect to an already-expired storage URL on a short-TTL deployment.
+func TestAvatarRedirectMaxAge_StaysBelowSignatureTTL(t *testing.T) {
+ origCfg := testHandler.cfg
+ t.Cleanup(func() { testHandler.cfg = origCfg })
+
+ for _, tc := range []struct {
+ ttl time.Duration
+ want int
+ }{
+ {0, avatarRedirectMaxAgeCap}, // unset -> 30m default
+ {30 * time.Minute, avatarRedirectMaxAgeCap},
+ {2 * time.Minute, avatarRedirectMaxAgeCap},
+ {30 * time.Second, 15},
+ {10 * time.Second, 5},
+ {time.Second, 0},
+ } {
+ testHandler.cfg.AttachmentDownloadURLTTL = tc.ttl
+ got := testHandler.avatarRedirectMaxAge()
+ if got != tc.want {
+ t.Errorf("ttl %s: avatarRedirectMaxAge = %d, want %d", tc.ttl, got, tc.want)
+ }
+ if ttl := int(testHandler.attachmentDownloadURLTTL() / time.Second); got >= ttl {
+ t.Errorf("ttl %s: cache max-age %d is not strictly below the signature lifetime %d", tc.ttl, got, ttl)
+ }
+ }
+}
+
+// TestServeAvatar_ShortTTLDisablesRedirectCaching — the header the clamp
+// actually produces at the low end.
+func TestServeAvatar_ShortTTLDisablesRedirectCaching(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+ testHandler.cfg.AttachmentDownloadURLTTL = time.Second
+ key := seedAvatarObject(t, avatarObjectOpts{})
+
+ w := serveAvatarRequest(t, signAvatarKey(key), key)
+ if w.Code != http.StatusFound {
+ t.Fatalf("status = %d, want 302", w.Code)
+ }
+ if got := w.Header().Get("Cache-Control"); got != "no-store" {
+ t.Fatalf("Cache-Control = %q, want no-store", got)
+ }
+}
+
+// TestServeAvatar_RejectsChannelMediaKey — channel ingest writes under
+// `workspaces/<ws>/lark/…` with no attachment row. Those are inbound chat
+// media, not avatars, so the namespace rule must fail closed on them rather
+// than treating "no row" as permission.
+func TestServeAvatar_RejectsChannelMediaKey(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+ key := "workspaces/" + testWorkspaceID + "/lark/" + uuid.NewString() + "/deadbeef.png"
+
+ if w := serveAvatarRequest(t, signAvatarKey(key), key); w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404 for a channel media key", w.Code)
+ }
+}
+
+// TestAvatarKeyIsPublishable_OperatorNamespace — an object the operator placed
+// in the bucket outside the upload flow stays usable. Only the workspace
+// namespace can hold content belonging to someone other than whoever is
+// setting the avatar, so only it has to prove itself; rejecting everything
+// else would break the documented "an explicit avatar_url is preserved"
+// contract for self-hosted deployments that host their own brand assets.
+func TestAvatarKeyIsPublishable_OperatorNamespace(t *testing.T) {
+ withAvatarStorage(t, &mockStorageNoCdn{}, "")
+
+ for _, key := range []string{"brand/logo.png", "avatars/agent.png"} {
+ if !testHandler.avatarKeyIsPublishable(context.Background(), key) {
+ t.Errorf("avatarKeyIsPublishable(%q) = false, want true", key)
+ }
+ if w := serveAvatarRequest(t, signAvatarKey(key), key); w.Code != http.StatusFound {
+ t.Errorf("serve %q: status = %d, want 302", key, w.Code)
+ }
+ }
+}
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index 1d9ddb882d..f13bb4cf6e 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -1117,11 +1117,11 @@ func commentAgentTriggerReason(trigger commentAgentTrigger) string {
}
}
-func commentAgentTriggerToResponse(trigger commentAgentTrigger) CommentTriggerAgentResponse {
+func (h *Handler) commentAgentTriggerToResponse(trigger commentAgentTrigger) CommentTriggerAgentResponse {
return CommentTriggerAgentResponse{
ID: uuidToString(trigger.Agent.ID),
Name: trigger.Agent.Name,
- AvatarURL: textToPtr(trigger.Agent.AvatarUrl),
+ AvatarURL: h.resolveAvatarURLPtr(textToPtr(trigger.Agent.AvatarUrl)),
Source: string(trigger.Source),
Reason: commentAgentTriggerReason(trigger),
}
@@ -1210,7 +1210,7 @@ func (h *Handler) PreviewCommentTriggers(w http.ResponseWriter, r *http.Request)
Blocked: commentBlockedTargetOutcomes(targets),
}
for _, trigger := range triggers {
- resp.Agents = append(resp.Agents, commentAgentTriggerToResponse(trigger))
+ resp.Agents = append(resp.Agents, h.commentAgentTriggerToResponse(trigger))
}
writeJSON(w, http.StatusOK, resp)
}
diff --git a/server/internal/handler/invitation.go b/server/internal/handler/invitation.go
index c020ffb72b..abe7832167 100644
--- a/server/internal/handler/invitation.go
+++ b/server/internal/handler/invitation.go
@@ -451,7 +451,7 @@ func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {
slog.Info("invitation accepted", "invitation_id", invitationID, "user_id", userID, "workspace_id", uuidToString(accepted.WorkspaceID))
wsID := uuidToString(accepted.WorkspaceID)
- memberResp := memberWithUserResponse(member, user)
+ memberResp := h.memberWithUserResponse(member, user)
// Broadcast member:added so existing clients update their member lists.
eventPayload := map[string]any{"member": memberResp}
diff --git a/server/internal/handler/onboarding.go b/server/internal/handler/onboarding.go
index 99e14cec75..dbc21152f2 100644
--- a/server/internal/handler/onboarding.go
+++ b/server/internal/handler/onboarding.go
@@ -124,7 +124,7 @@ func (h *Handler) CompleteOnboarding(w http.ResponseWriter, r *http.Request) {
))
}
- writeJSON(w, http.StatusOK, userToResponse(user))
+ writeJSON(w, http.StatusOK, h.userToResponse(user))
}
type patchOnboardingRequest struct {
@@ -306,7 +306,7 @@ func (h *Handler) PatchOnboarding(w http.ResponseWriter, r *http.Request) {
))
}
- writeJSON(w, http.StatusOK, userToResponse(user))
+ writeJSON(w, http.StatusOK, h.userToResponse(user))
}
type joinCloudWaitlistRequest struct {
@@ -368,5 +368,5 @@ func (h *Handler) JoinCloudWaitlist(w http.ResponseWriter, r *http.Request) {
obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.CloudWaitlistJoined(userID, reason != ""))
- writeJSON(w, http.StatusOK, userToResponse(user))
+ writeJSON(w, http.StatusOK, h.userToResponse(user))
}
diff --git a/server/internal/handler/onboarding_shim.go b/server/internal/handler/onboarding_shim.go
index f460cc6b57..4e1f9eb194 100644
--- a/server/internal/handler/onboarding_shim.go
+++ b/server/internal/handler/onboarding_shim.go
@@ -308,7 +308,7 @@ func (h *Handler) BootstrapOnboardingRuntime(w http.ResponseWriter, r *http.Requ
}
if assistantCreated {
- resp := agentToResponse(assistant)
+ resp := h.agentToResponse(assistant)
h.publish(protocol.EventAgentCreated, req.WorkspaceID, "member", userID, map[string]any{"agent": resp})
obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.AgentCreated(
userID, req.WorkspaceID, uuidToString(assistant.ID),
diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.go
index 3020da95eb..e2672f1d7c 100644
--- a/server/internal/handler/runtime.go
+++ b/server/internal/handler/runtime.go
@@ -777,7 +777,7 @@ func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {
return
}
if len(activeAgents) > 0 {
- writeJSON(w, http.StatusConflict, runtimeHasActiveAgentsResponse(activeAgents))
+ writeJSON(w, http.StatusConflict, h.runtimeHasActiveAgentsResponse(activeAgents))
return
}
@@ -903,10 +903,10 @@ func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {
//
// Front-end branches on `code`. The caller picks which code to send; this
// helper just normalises the agent serialisation and the error string.
-func runtimeHasActiveAgentsResponse(agents []db.Agent) map[string]any {
+func (h *Handler) runtimeHasActiveAgentsResponse(agents []db.Agent) map[string]any {
resp := make([]AgentResponse, len(agents))
for i, a := range agents {
- resp[i] = agentToResponse(a)
+ resp[i] = h.agentToResponse(a)
}
return map[string]any{
"error": "cannot delete runtime: it has active agents bound to it. Archive or reassign the agents first.",
@@ -1038,7 +1038,7 @@ func (h *Handler) ArchiveAgentsAndDeleteRuntime(w http.ResponseWriter, r *http.R
// shared response helper but overrides the code to a planning
// signal so the dialog can distinguish "you opened from a stale
// page" from "the plan you confirmed just changed under you".
- body := runtimeHasActiveAgentsResponse(currentActive)
+ body := h.runtimeHasActiveAgentsResponse(currentActive)
body["code"] = "runtime_delete_plan_changed"
body["error"] = "the active agent set changed; please review and confirm again."
writeJSON(w, http.StatusConflict, body)
@@ -1164,7 +1164,7 @@ func (h *Handler) ArchiveAgentsAndDeleteRuntime(w http.ResponseWriter, r *http.R
}
for _, a := range archivedAgents {
h.publish(protocol.EventAgentArchived, wsID, "member", userID, map[string]any{
- "agent": agentToResponse(a),
+ "agent": h.agentToResponse(a),
})
}
h.publish(protocol.EventDaemonRegister, wsID, "member", userID, map[string]any{
diff --git a/server/internal/handler/squad.go b/server/internal/handler/squad.go
index af8caf987d..ed4368e8a7 100644
--- a/server/internal/handler/squad.go
+++ b/server/internal/handler/squad.go
@@ -58,14 +58,14 @@ type SquadMemberResponse struct {
// ── Converters ──────────────────────────────────────────────────────────────
-func squadToResponse(s db.Squad) SquadResponse {
+func (h *Handler) squadToResponse(s db.Squad) SquadResponse {
return SquadResponse{
ID: uuidToString(s.ID),
WorkspaceID: uuidToString(s.WorkspaceID),
Name: s.Name,
Description: s.Description,
Instructions: s.Instructions,
- AvatarURL: textToPtr(s.AvatarUrl),
+ AvatarURL: h.resolveAvatarURLPtr(textToPtr(s.AvatarUrl)),
LeaderID: uuidToString(s.LeaderID),
CreatorID: uuidToString(s.CreatorID),
CreatedAt: timestampToString(s.CreatedAt),
@@ -175,7 +175,7 @@ func (h *Handler) loadSquadMemberSummary(ctx context.Context, squadID pgtype.UUI
}
func (h *Handler) squadToResponseWithPreview(ctx context.Context, squad db.Squad) (SquadResponse, error) {
- resp := squadToResponse(squad)
+ resp := h.squadToResponse(squad)
summary, err := h.loadSquadMemberSummary(ctx, squad.ID)
if err != nil {
return resp, err
@@ -216,7 +216,7 @@ func (h *Handler) ListSquads(w http.ResponseWriter, r *http.Request) {
resp := make([]SquadResponse, len(squads))
for i, s := range squads {
- resp[i] = squadToResponse(s)
+ resp[i] = h.squadToResponse(s)
applySquadMemberSummary(&resp[i], summaries[uuidToString(s.ID)])
}
writeJSON(w, http.StatusOK, resp)
@@ -278,7 +278,11 @@ func (h *Handler) CreateSquad(w http.ResponseWriter, r *http.Request) {
avatarURL := pgtype.Text{}
if req.AvatarURL != nil {
- avatarURL = pgtype.Text{String: *req.AvatarURL, Valid: true}
+ accepted, ok := h.acceptAvatarURL(w, r, *req.AvatarURL, "")
+ if !ok {
+ return
+ }
+ avatarURL = pgtype.Text{String: accepted, Valid: true}
}
squad, err := h.Queries.CreateSquad(r.Context(), db.CreateSquadParams{
@@ -373,7 +377,11 @@ func (h *Handler) UpdateSquad(w http.ResponseWriter, r *http.Request) {
params.Instructions = pgtype.Text{String: *req.Instructions, Valid: true}
}
if req.AvatarURL != nil {
- params.AvatarUrl = pgtype.Text{String: *req.AvatarURL, Valid: true}
+ accepted, ok := h.acceptAvatarURL(w, r, *req.AvatarURL, squad.AvatarUrl.String)
+ if !ok {
+ return
+ }
+ params.AvatarUrl = pgtype.Text{String: accepted, Valid: true}
}
if req.LeaderID != nil {
lid, ok := parseUUIDOrBadRequest(w, *req.LeaderID, "leader_id")
diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.go
index 08480bf3d4..0cb02f6194 100644
--- a/server/internal/handler/workspace.go
+++ b/server/internal/handler/workspace.go
@@ -48,7 +48,7 @@ type WorkspaceResponse struct {
UpdatedAt string `json:"updated_at"`
}
-func workspaceToResponse(w db.Workspace) WorkspaceResponse {
+func (h *Handler) workspaceToResponse(w db.Workspace) WorkspaceResponse {
var settings any
if w.Settings != nil {
json.Unmarshal(w.Settings, &settings)
@@ -72,7 +72,7 @@ func workspaceToResponse(w db.Workspace) WorkspaceResponse {
Settings: settings,
Repos: repos,
IssuePrefix: w.IssuePrefix,
- AvatarURL: textToPtr(w.AvatarUrl),
+ AvatarURL: h.resolveAvatarURLPtr(textToPtr(w.AvatarUrl)),
CreatedAt: timestampToString(w.CreatedAt),
UpdatedAt: timestampToString(w.UpdatedAt),
}
@@ -110,7 +110,7 @@ func (h *Handler) ListWorkspaces(w http.ResponseWriter, r *http.Request) {
resp := make([]WorkspaceResponse, len(workspaces))
for i, ws := range workspaces {
- resp[i] = workspaceToResponse(ws)
+ resp[i] = h.workspaceToResponse(ws)
}
writeJSON(w, http.StatusOK, resp)
@@ -128,7 +128,7 @@ func (h *Handler) GetWorkspace(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotFound, "workspace not found")
return
}
- writeJSON(w, http.StatusOK, workspaceToResponse(ws))
+ writeJSON(w, http.StatusOK, h.workspaceToResponse(ws))
}
type CreateWorkspaceRequest struct {
@@ -238,7 +238,7 @@ func (h *Handler) CreateWorkspace(w http.ResponseWriter, r *http.Request) {
h.notifyDaemonWorkspacesChanged(userID)
slog.Info("workspace created", append(logger.RequestAttrs(r), "workspace_id", wsID, "name", ws.Name, "slug", ws.Slug)...)
- writeJSON(w, http.StatusCreated, workspaceToResponse(ws))
+ writeJSON(w, http.StatusCreated, h.workspaceToResponse(ws))
}
type UpdateWorkspaceRequest struct {
@@ -341,7 +341,18 @@ func (h *Handler) UpdateWorkspace(w http.ResponseWriter, r *http.Request) {
}
}
if req.AvatarURL != nil {
- params.AvatarUrl = pgtype.Text{String: *req.AvatarURL, Valid: true}
+ // Read the stored value so an unchanged re-send skips revalidation —
+ // this handler is the one avatar writer that doesn't already have the
+ // row in hand.
+ var current string
+ if existing, err := h.Queries.GetWorkspace(r.Context(), idUUID); err == nil {
+ current = existing.AvatarUrl.String
+ }
+ accepted, ok := h.acceptAvatarURL(w, r, *req.AvatarURL, current)
+ if !ok {
+ return
+ }
+ params.AvatarUrl = pgtype.Text{String: accepted, Valid: true}
}
ws, err := h.Queries.UpdateWorkspace(r.Context(), params)
@@ -353,7 +364,7 @@ func (h *Handler) UpdateWorkspace(w http.ResponseWriter, r *http.Request) {
slog.Info("workspace updated", append(logger.RequestAttrs(r), "workspace_id", id)...)
userID := requestUserID(r)
- h.publish(protocol.EventWorkspaceUpdated, uuidToString(ws.ID), "member", userID, map[string]any{"workspace": workspaceToResponse(ws)})
+ h.publish(protocol.EventWorkspaceUpdated, uuidToString(ws.ID), "member", userID, map[string]any{"workspace": h.workspaceToResponse(ws)})
if req.Name != nil {
if members, err := h.Queries.ListMembers(r.Context(), ws.ID); err == nil {
userIDs := make([]string, 0, len(members))
@@ -364,7 +375,7 @@ func (h *Handler) UpdateWorkspace(w http.ResponseWriter, r *http.Request) {
}
}
- writeJSON(w, http.StatusOK, workspaceToResponse(ws))
+ writeJSON(w, http.StatusOK, h.workspaceToResponse(ws))
}
func (h *Handler) ListMembers(w http.ResponseWriter, r *http.Request) {
@@ -422,7 +433,7 @@ func (h *Handler) ListMembersWithUser(w http.ResponseWriter, r *http.Request) {
CreatedAt: timestampToString(m.CreatedAt),
Name: m.UserName,
Email: m.UserEmail,
- AvatarURL: textToPtr(m.UserAvatarUrl),
+ AvatarURL: h.resolveAvatarURLPtr(textToPtr(m.UserAvatarUrl)),
}
}
@@ -434,7 +445,7 @@ type CreateMemberRequest struct {
Role string `json:"role"`
}
-func memberWithUserResponse(member db.Member, user db.User) MemberWithUserResponse {
+func (h *Handler) memberWithUserResponse(member db.Member, user db.User) MemberWithUserResponse {
return MemberWithUserResponse{
ID: uuidToString(member.ID),
WorkspaceID: uuidToString(member.WorkspaceID),
@@ -443,7 +454,7 @@ func memberWithUserResponse(member db.Member, user db.User) MemberWithUserRespon
CreatedAt: timestampToString(member.CreatedAt),
Name: user.Name,
Email: user.Email,
- AvatarURL: textToPtr(user.AvatarUrl),
+ AvatarURL: h.resolveAvatarURLPtr(textToPtr(user.AvatarUrl)),
}
}
@@ -525,14 +536,14 @@ func (h *Handler) CreateMember(w http.ResponseWriter, r *http.Request) {
slog.Info("member added", append(logger.RequestAttrs(r), "member_id", uuidToString(member.ID), "workspace_id", workspaceID, "email", email, "role", role)...)
userID := requestUserID(r)
- eventPayload := map[string]any{"member": memberWithUserResponse(member, user)}
+ eventPayload := map[string]any{"member": h.memberWithUserResponse(member, user)}
if ws, err := h.Queries.GetWorkspace(r.Context(), requester.WorkspaceID); err == nil {
eventPayload["workspace_name"] = ws.Name
}
h.publish(protocol.EventMemberAdded, uuidToString(requester.WorkspaceID), "member", userID, eventPayload)
h.notifyDaemonWorkspacesChanged(uuidToString(user.ID))
- writeJSON(w, http.StatusCreated, memberWithUserResponse(member, user))
+ writeJSON(w, http.StatusCreated, h.memberWithUserResponse(member, user))
}
type UpdateMemberRequest struct {
@@ -609,10 +620,10 @@ func (h *Handler) UpdateMember(w http.ResponseWriter, r *http.Request) {
userID := requestUserID(r)
h.publish(protocol.EventMemberUpdated, uuidToString(requester.WorkspaceID), "member", userID, map[string]any{
- "member": memberWithUserResponse(updatedMember, user),
+ "member": h.memberWithUserResponse(updatedMember, user),
})
- writeJSON(w, http.StatusOK, memberWithUserResponse(updatedMember, user))
+ writeJSON(w, http.StatusOK, h.memberWithUserResponse(updatedMember, user))
}
func (h *Handler) DeleteMember(w http.ResponseWriter, r *http.Request) {
diff --git a/server/internal/handler/workspace_revoke.go b/server/internal/handler/workspace_revoke.go
index f474425892..0dfca30b8f 100644
--- a/server/internal/handler/workspace_revoke.go
+++ b/server/internal/handler/workspace_revoke.go
@@ -193,7 +193,7 @@ func (h *Handler) publishRevocation(ctx context.Context, result revocationResult
for _, agent := range result.ArchivedAgents {
h.publish(protocol.EventAgentArchived, workspaceIDStr, actorType, actorIDStr, map[string]any{
- "agent": agentToResponse(agent),
+ "agent": h.agentToResponse(agent),
})
}