Files
multica/server/internal/middleware/daemon_auth.go
Bohan Jiang 22136a55fc fix(server/heartbeat): split auth_ms into decode/runtime_lookup/workspace_check + auth_path (#1822)
Prod slow-log on the deployed v0.2.17 fix shows total_ms=4012,
auth_ms=4010, update_ms=1, all skill stages = 0 — meaning the bottleneck
on /api/daemon/heartbeat is now the auth section, not the Redis claim
path. To pinpoint which sub-stage dominates, decompose auth_ms into:

- decode_ms        — JSON body decode
- runtime_lookup_ms — Queries.GetAgentRuntime (PG PK select)
- workspace_check_ms — requireDaemonWorkspaceAccess (string compare for
                       daemon-token, requireWorkspaceMember for PAT/JWT)

Also add auth_path ("daemon_token" | "pat" | "jwt") set by DaemonAuth
middleware so slow-logs disambiguate which token kind was used. PAT/JWT
takes an extra DB round-trip via requireWorkspaceMember and is a
candidate cause of long auth tails on daemons that haven't migrated to
mdt_ tokens.

The handler keeps the same external behavior; the change inlines and
instruments requireDaemonRuntimeAccess in DaemonHeartbeat only — other
callers of the helper are untouched. logHeartbeatEndpointSlow gains the
new fields.

Existing heartbeat tests pass; the slow-probe test output now shows the
new auth_path / decode_ms / runtime_lookup_ms / workspace_check_ms
fields populated.
2026-04-29 15:00:00 +08:00

141 lines
4.8 KiB
Go

package middleware
import (
"context"
"log/slog"
"net/http"
"strings"
"github.com/golang-jwt/jwt/v5"
"github.com/multica-ai/multica/server/internal/auth"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
// Daemon context keys.
type daemonContextKey int
const (
ctxKeyDaemonWorkspaceID daemonContextKey = iota
ctxKeyDaemonID
ctxKeyDaemonAuthPath
)
// Daemon auth path labels exposed via context for slow-log attribution.
const (
DaemonAuthPathDaemonToken = "daemon_token"
DaemonAuthPathPAT = "pat"
DaemonAuthPathJWT = "jwt"
)
// DaemonWorkspaceIDFromContext returns the workspace ID set by DaemonAuth middleware.
func DaemonWorkspaceIDFromContext(ctx context.Context) string {
id, _ := ctx.Value(ctxKeyDaemonWorkspaceID).(string)
return id
}
// DaemonIDFromContext returns the daemon ID set by DaemonAuth middleware.
func DaemonIDFromContext(ctx context.Context) string {
id, _ := ctx.Value(ctxKeyDaemonID).(string)
return id
}
// DaemonAuthPathFromContext returns which token kind authenticated this
// request — "daemon_token", "pat", or "jwt" — for telemetry. Empty when the
// request did not pass through DaemonAuth.
func DaemonAuthPathFromContext(ctx context.Context) string {
p, _ := ctx.Value(ctxKeyDaemonAuthPath).(string)
return p
}
// WithDaemonContext returns a new context with the daemon workspace ID and daemon ID set.
// This is used by tests to simulate daemon token authentication.
func WithDaemonContext(ctx context.Context, workspaceID, daemonID string) context.Context {
ctx = context.WithValue(ctx, ctxKeyDaemonWorkspaceID, workspaceID)
ctx = context.WithValue(ctx, ctxKeyDaemonID, daemonID)
ctx = context.WithValue(ctx, ctxKeyDaemonAuthPath, DaemonAuthPathDaemonToken)
return ctx
}
// DaemonAuth validates daemon auth tokens (mdt_ prefix) or falls back to
// JWT/PAT validation for backward compatibility with daemons that
// authenticate via user tokens.
func DaemonAuth(queries *db.Queries) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
slog.Debug("daemon_auth: missing authorization header", "path", r.URL.Path)
writeError(w, http.StatusUnauthorized, "missing authorization header")
return
}
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
if tokenString == authHeader {
slog.Debug("daemon_auth: invalid format", "path", r.URL.Path)
writeError(w, http.StatusUnauthorized, "invalid authorization format")
return
}
// Daemon token: "mdt_" prefix.
if strings.HasPrefix(tokenString, "mdt_") {
hash := auth.HashToken(tokenString)
dt, err := queries.GetDaemonTokenByHash(r.Context(), hash)
if err != nil {
slog.Warn("daemon_auth: invalid daemon token", "path", r.URL.Path, "error", err)
writeError(w, http.StatusUnauthorized, "invalid daemon token")
return
}
ctx := context.WithValue(r.Context(), ctxKeyDaemonWorkspaceID, uuidToString(dt.WorkspaceID))
ctx = context.WithValue(ctx, ctxKeyDaemonID, dt.DaemonID)
ctx = context.WithValue(ctx, ctxKeyDaemonAuthPath, DaemonAuthPathDaemonToken)
next.ServeHTTP(w, r.WithContext(ctx))
return
}
// Fallback: PAT tokens ("mul_" prefix).
if strings.HasPrefix(tokenString, "mul_") {
hash := auth.HashToken(tokenString)
pat, err := queries.GetPersonalAccessTokenByHash(r.Context(), hash)
if err != nil {
slog.Warn("daemon_auth: invalid PAT", "path", r.URL.Path, "error", err)
writeError(w, http.StatusUnauthorized, "invalid token")
return
}
r.Header.Set("X-User-ID", uuidToString(pat.UserID))
go queries.UpdatePersonalAccessTokenLastUsed(context.Background(), pat.ID)
ctx := context.WithValue(r.Context(), ctxKeyDaemonAuthPath, DaemonAuthPathPAT)
next.ServeHTTP(w, r.WithContext(ctx))
return
}
// Fallback: JWT tokens.
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, jwt.ErrSignatureInvalid
}
return auth.JWTSecret(), nil
})
if err != nil || !token.Valid {
slog.Warn("daemon_auth: invalid token", "path", r.URL.Path, "error", err)
writeError(w, http.StatusUnauthorized, "invalid token")
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
writeError(w, http.StatusUnauthorized, "invalid claims")
return
}
sub, ok := claims["sub"].(string)
if !ok || strings.TrimSpace(sub) == "" {
writeError(w, http.StatusUnauthorized, "invalid claims")
return
}
r.Header.Set("X-User-ID", sub)
ctx := context.WithValue(r.Context(), ctxKeyDaemonAuthPath, DaemonAuthPathJWT)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}