Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(auth): support mcn_ Cloud Node PATs verified via Fleet (#3349)
LinYushenc968c13c879f
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex 81ebab4dd6..a34c76f11d 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -152,7 +152,7 @@ describe("ApiClient", () => {expect(headers["X-Client-OS"]).toBeUndefined();});- it("uses the Cloud Runtime node API contract and forwards bootstrap PAT on create", async () => {+ it("uses the Cloud Runtime node API contract", async () => {const node = {id: "node-1",owner_id: "user-1",@@ -195,7 +195,6 @@ describe("ApiClient", () => {expect(listCall[0]).toBe("https://api.example.test/api/cloud-runtime/nodes?limit=20&offset=5",);- expect((listCall[1]!.headers as Record<string, string>)["X-User-PAT"]).toBeUndefined();expect(createCall[0]).toBe("https://api.example.test/api/cloud-runtime/nodes",);@@ -206,7 +205,6 @@ describe("ApiClient", () => {name: "gpu-dev-01",}),});- expect((createCall[1]!.headers as Record<string, string>)["X-User-PAT"]).toBeUndefined();});it("falls back when Cloud Runtime node responses drift", async () => {diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex d0ae903084..11cea942df 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -166,6 +166,17 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bush.DaemonTokenCache = daemonTokenCacheh.MembershipCache = auth.NewMembershipCache(rdb)+ // Cloud PAT verifier: validates mcn_ tokens against Multica Cloud+ // Fleet. Returns nil when no Fleet URL is configured — the Auth /+ // DaemonAuth middlewares treat nil as "mcn_ not supported" and+ // reject with 401, instead of falling through to mul_/JWT paths.+ // Reuses MULTICA_CLOUD_FLEET_URL (the same URL the cloud-runtime+ // proxy uses) so a deployment doesn't need a second config knob.+ cloudPATVerifier := auth.NewCloudPATVerifier(auth.CloudPATVerifierConfig{+ FleetBaseURL: signupConfig.CloudRuntimeFleetURL,+ Redis: rdb,+ })+// Empty-claim cache: lets the daemon poll path skip a Postgres// scan when a recent check confirmed the runtime had no queued// task. Returns nil when rdb is nil — TaskService treats that@@ -196,7 +207,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Use(cors.Handler(cors.Options{AllowedOrigins: origins,AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},- AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-Workspace-ID", "X-Workspace-Slug", "X-Request-ID", "X-Agent-ID", "X-Task-ID", "X-CSRF-Token", "X-Client-Platform", "X-Client-Version", "X-Client-OS", "X-User-PAT"},+ AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-Workspace-ID", "X-Workspace-Slug", "X-Request-ID", "X-Agent-ID", "X-Task-ID", "X-CSRF-Token", "X-Client-Platform", "X-Client-Version", "X-Client-OS"},AllowCredentials: true,MaxAge: 300,}))@@ -267,7 +278,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Daemon API routes (require daemon token or valid user token)r.Route("/api/daemon", func(r chi.Router) {- r.Use(middleware.DaemonAuth(queries, patCache, daemonTokenCache))+ r.Use(middleware.DaemonAuth(queries, patCache, daemonTokenCache, cloudPATVerifier))r.Post("/register", h.DaemonRegister)r.Post("/deregister", h.DaemonDeregister)@@ -303,7 +314,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Protected API routesr.Group(func(r chi.Router) {- r.Use(middleware.Auth(queries, patCache))+ r.Use(middleware.Auth(queries, patCache, cloudPATVerifier))r.Use(middleware.RefreshCloudFrontCookies(cfSigner))// --- User-scoped routes (no workspace context required) ---diff --git a/server/internal/auth/cloud_pat.go b/server/internal/auth/cloud_pat.gonew file mode 100644index 0000000000..e61022f85a--- /dev/null+++ b/server/internal/auth/cloud_pat.go@@ -0,0 +1,440 @@+package auth++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "net/http"+ "strings"+ "time"++ "github.com/redis/go-redis/v9"+)++// CloudPATPrefix is the literal token prefix that identifies an mcn_+// (Multica Cloud Node) PAT. Tokens with this prefix are validated by+// calling the Multica Cloud Fleet service rather than by hitting our+// local personal_access_tokens table — the cloud is the authoritative+// owner of the token's lifecycle, status, and (owner_id, instance_id)+// binding.+const CloudPATPrefix = "mcn_"++// cloudPATCachePrefix namespaces cloud-PAT cache keys away from+// mul_/mdt_ caches so the three token kinds can't accidentally share+// keys. The trailing slash mirrors the existing patCachePrefix /+// daemonTokenCachePrefix conventions.+const cloudPATCachePrefix = "mul:auth:mcn:"++// cloudPATCacheTTL bounds how long a verified mcn_ token stays cached+// before we re-ask Fleet. The Cloud doc explicitly recommends 30–60s+// "if upstream really needs to cache" — anything longer widens the+// revocation window beyond what Cloud is comfortable with. We pick the+// upper bound: short enough that a revoked / instance-terminated PAT+// stops working within ~1 minute, long enough that a busy daemon /+// CLI on a node collapses to one verify call per minute per token.+//+// We deliberately do NOT reuse AuthCacheTTL (10m) — that's tuned for+// our own DB-backed PAT/daemon-token paths where revocation+// invalidates the cache key directly. We have no way to invalidate+// when Cloud revokes a PAT, so the TTL itself IS the revocation+// latency bound.+const cloudPATCacheTTL = 60 * time.Second++// cloudPATVerifyPath is the Fleet endpoint we POST to. The Cloud doc+// places this under /api/v1/pat/verify; the upstream runs no app-layer+// auth on it (network-level VPC isolation is the access control), so+// we just send the token plaintext and let Fleet decide.+const cloudPATVerifyPath = "/api/v1/pat/verify"++// cloudPATVerifyRequestMaxBytes is the documented Fleet hard cap on+// request bodies (4 KiB). Our marshalled requests are well under that+// — this constant exists to make the intent visible if anyone adds+// optional fields later.+const cloudPATVerifyRequestMaxBytes = 4 * 1024++// cloudPATVerifyResponseMaxBytes bounds how much of a Fleet response+// we'll read. The success payload is well under 1 KiB; we pick 64 KiB+// to stay well clear of pathological responses without enabling a+// memory-exhaustion vector via a misbehaving Fleet.+const cloudPATVerifyResponseMaxBytes = 64 * 1024++// cloudPATDefaultTimeout is the per-request HTTP timeout for verify+// calls when the caller doesn't supply an *http.Client. Auth must+// stay snappy: Fleet should answer in tens of milliseconds, and a+// hung verify would block every incoming request behind it. Tighter+// than cloudruntime's 35s because that one proxies arbitrary user+// traffic; this one only ever sees a small JSON exchange.+const cloudPATDefaultTimeout = 5 * time.Second++// Verifier sentinel errors. Callers (the Auth / DaemonAuth middlewares)+// branch on these to map cloud outcomes onto HTTP status codes:+//+// - ErrCloudPATInvalid → 401 (Fleet says token is bad)+// - ErrCloudPATUnavailable → 503 (Fleet unreachable / 5xx)+// - ErrCloudPATNotConfigured → 401 (server has no Fleet URL set; we+// don't reveal that mcn_ is "supported but disabled" — failing+// closed avoids treating misconfigured prod the same as enabled)+var (+ ErrCloudPATInvalid = errors.New("cloud pat invalid")+ ErrCloudPATUnavailable = errors.New("cloud pat verifier unavailable")+ ErrCloudPATNotConfigured = errors.New("cloud pat verifier not configured")+)++// CloudPATIdentity is what a successful verify resolves to. We keep+// only the fields the auth path actually needs:+//+// - OwnerID is the user whose request this is (mapped to X-User-ID).+// - InstanceID / InstanceRecordID are recorded so downstream code can+// correlate the request with a specific cloud node; they are not+// used for authorization today, but stashing them now keeps the+// wire shape stable for callers that later want to assert a+// particular instance binding.+//+// We deliberately drop token_last4, status, issued_at, etc. — those+// are diagnostic fields that don't belong in cached auth state.+type CloudPATIdentity struct {+ OwnerID string `json:"o"`+ InstanceID string `json:"i"`+ InstanceRecordID string `json:"r"`+}++// CloudPATInvalidError carries the Fleet-reported reason for a+// valid=false response. The middleware uses this to log why an mcn_+// token was rejected without exposing the reason in the 401 body —+// per the Cloud doc, callers shouldn't differentiate token_not_found+// vs token_revoked for security decisions.+//+// The "owner_unknown" reason is also produced locally by Verify when+// Cloud accepted the token but the returned owner_id does not map to+// a real user in our DB. Treating that as a Cloud-style "invalid"+// keeps the middleware's response shape uniform — the result is the+// same: 401, drop the token.+type CloudPATInvalidError struct {+ Reason string+}++func (e *CloudPATInvalidError) Error() string {+ if e == nil || e.Reason == "" {+ return "cloud pat invalid"+ }+ return "cloud pat invalid: " + e.Reason+}++// Is lets errors.Is(err, ErrCloudPATInvalid) match any+// CloudPATInvalidError, so callers can branch on the category without+// caring about the exact reason string.+func (e *CloudPATInvalidError) Is(target error) bool {+ return target == ErrCloudPATInvalid+}++// CloudPATInvalidReasonOwnerUnknown is the synthetic reason emitted+// when Cloud verified the token but the returned owner_id was not+// found in the local users table. The Cloud `owner_id` and our+// `users.id` share the same UUID space by contract; a mismatch means+// either the user has been deleted on our side after the node was+// minted, or (worse) something is impersonating Cloud and trying to+// surface a forged owner_id. Either way the request must be rejected.+const CloudPATInvalidReasonOwnerUnknown = "owner_unknown"++// OwnerLookupFunc is the user-existence check Verify runs against+// Cloud's owner_id before caching / returning the identity. The+// caller (typically the middleware closure) wires it to a+// queries.GetUser call.+//+// Return semantics:+// - (true, nil) → owner_id is a valid local user; Verify returns success.+// - (false, nil) → owner_id does not exist locally; Verify returns+// ErrCloudPATInvalid with reason="owner_unknown" and does NOT+// cache (a missing user can be re-created later, and we don't+// want to lock that retry out for a TTL window).+// - (_, err) → infrastructure error (DB unreachable, etc.);+// Verify wraps as ErrCloudPATUnavailable so the caller emits 503,+// not 401.+type OwnerLookupFunc func(ctx context.Context, ownerID string) (bool, error)++// CloudPATVerifier resolves mcn_ PATs by calling+// POST <fleetURL>/api/v1/pat/verify and caches verified results in+// Redis for cloudPATCacheTTL.+//+// A nil *CloudPATVerifier is safe — Verify returns+// ErrCloudPATNotConfigured. The Auth/DaemonAuth middlewares treat+// "verifier nil" the same as "fleet URL empty", so a server with no+// MULTICA_CLOUD_FLEET_URL configured simply rejects mcn_ tokens at+// the prefix branch instead of nil-derefing.+type CloudPATVerifier struct {+ baseURL string+ http *http.Client+ rdb *redis.Client // may be nil — disables caching+}++// CloudPATVerifierConfig assembles the dependencies for+// NewCloudPATVerifier. Keeping this a struct (vs positional args)+// leaves room for future knobs (custom TTL, expected_owner_id binding)+// without churning every call site.+type CloudPATVerifierConfig struct {+ // FleetBaseURL is the Cloud Fleet base URL (e.g.+ // https://fleet.multica.cloud). Trailing slashes are trimmed.+ // Empty disables the verifier — NewCloudPATVerifier returns nil.+ FleetBaseURL string++ // HTTPClient is the client used for verify calls. Optional —+ // when nil, a client with cloudPATDefaultTimeout is created.+ // Pass a shared client when you want connection pooling /+ // per-deployment transport tuning.+ HTTPClient *http.Client++ // Redis backs the positive-result cache. Nil disables caching —+ // every Verify call hits Fleet. Same nil-safe contract as+ // PATCache / DaemonTokenCache.+ Redis *redis.Client+}++// NewCloudPATVerifier returns a verifier for cfg.FleetBaseURL. If the+// URL is empty after trimming, returns nil — callers (router /+// middleware) treat nil as "mcn_ not supported on this deployment".+func NewCloudPATVerifier(cfg CloudPATVerifierConfig) *CloudPATVerifier {+ base := strings.TrimRight(strings.TrimSpace(cfg.FleetBaseURL), "/")+ if base == "" {+ return nil+ }+ client := cfg.HTTPClient+ if client == nil {+ client = &http.Client{Timeout: cloudPATDefaultTimeout}+ }+ return &CloudPATVerifier{+ baseURL: base,+ http: client,+ rdb: cfg.Redis,+ }+}++// Configured reports whether the verifier has a Fleet URL. Convenience+// for telemetry — a nil receiver also returns false. The middleware+// uses ordinary nil checks instead of this in hot paths.+func (v *CloudPATVerifier) Configured() bool {+ return v != nil && v.baseURL != ""+}++// Verify resolves token to a CloudPATIdentity by consulting (in order):+//+// 1. Redis cache, keyed by sha256(token). Hit → return cached+// identity, no Fleet round-trip and no DB lookup. The cache only+// ever contains identities that have already passed both Cloud's+// verify AND the local owner-existence check, so a cache hit is+// a fully-validated decision.+// 2. Fleet POST /api/v1/pat/verify. The response distinguishes:+// - HTTP 200 + valid=true → continues to step 3+// - HTTP 200 + valid=false → CloudPATInvalidError{Reason:...}+// (also wraps as ErrCloudPATInvalid via Is)+// - HTTP 4xx/5xx, network, timeout, decode failure+// → ErrCloudPATUnavailable+// 3. Local owner-existence check via lookup(owner_id):+// - exists → cache + return success+// - missing → ErrCloudPATInvalid (reason="owner_unknown"), NOT cached+// - error → ErrCloudPATUnavailable+//+// `lookup` may be nil — Verify then skips step 3. Production callers+// (Auth / DaemonAuth) always supply one; nil mode is for unit tests+// that exercise the verifier in isolation from the DB.+//+// We deliberately do NOT cache valid=false responses or+// owner_unknown rejections — per the Cloud doc, negative results can+// flip back to positive (lazy-revoke reconciliation, owner created+// later in our DB), and a stale negative would permanently lock out+// a freshly minted token within the TTL window.+//+// On a nil receiver returns ErrCloudPATNotConfigured so the+// middleware can map mcn_ tokens to 401 cleanly when the deployment+// has no Fleet URL.+func (v *CloudPATVerifier) Verify(ctx context.Context, token string, lookup OwnerLookupFunc) (CloudPATIdentity, error) {+ if v == nil || v.baseURL == "" {+ return CloudPATIdentity{}, ErrCloudPATNotConfigured+ }+ if token == "" {+ return CloudPATIdentity{}, ErrCloudPATInvalid+ }++ hash := HashToken(token)+ if id, ok := v.cacheGet(ctx, hash); ok {+ return id, nil+ }++ id, err := v.fetch(ctx, token)+ if err != nil {+ return CloudPATIdentity{}, err+ }++ if lookup != nil {+ exists, lookupErr := lookup(ctx, id.OwnerID)+ if lookupErr != nil {+ // Treat a DB / infrastructure error the same as a Cloud+ // outage: surface 503 so the caller retries instead of+ // throwing out a still-valid token. The cache is NOT+ // populated, so a transient blip resolves on the next+ // request.+ slog.Warn("cloud_pat: owner lookup failed; treating as unavailable", "error", lookupErr)+ return CloudPATIdentity{}, ErrCloudPATUnavailable+ }+ if !exists {+ // Cloud accepted the token, but the owner_id it returned+ // is not a user we know. Reject without caching — if the+ // user is created later, the next request must succeed+ // without waiting for the TTL.+ slog.Warn("cloud_pat: cloud-verified owner_id has no local user", "owner_id", id.OwnerID)+ return CloudPATIdentity{}, &CloudPATInvalidError{Reason: CloudPATInvalidReasonOwnerUnknown}+ }+ }++ v.cacheSet(ctx, hash, id)+ return id, nil+}++// fleetVerifyRequest mirrors the Cloud doc's request schema. We only+// send `token` today — `expected_owner_id` / `expected_instance_id`+// would let the verifier fail a token bound to a different user than+// the request claims, but at this layer we don't yet know the+// "claimed" user. Wiring those in is a future hardening step.+type fleetVerifyRequest struct {+ Token string `json:"token"`+}++// fleetVerifyResponse is the union response shape. `Valid` discriminates+// the two arms; on `valid:false` only `Reason` is meaningful (per the+// Cloud doc, mismatch responses deliberately omit binding info to+// avoid serving as a probing oracle).+type fleetVerifyResponse struct {+ Valid bool `json:"valid"`+ Reason string `json:"reason,omitempty"`+ OwnerID string `json:"owner_id,omitempty"`+ InstanceID string `json:"instance_id,omitempty"`+ InstanceRecordID string `json:"instance_record_id,omitempty"`+}++func (v *CloudPATVerifier) fetch(ctx context.Context, token string) (CloudPATIdentity, error) {+ body, err := json.Marshal(fleetVerifyRequest{Token: token})+ if err != nil {+ // json.Marshal of a fixed struct with a string field cannot+ // realistically fail; surfacing as Unavailable keeps callers+ // on the "treat as cloud error" branch.+ return CloudPATIdentity{}, fmt.Errorf("%w: marshal request: %v", ErrCloudPATUnavailable, err)+ }+ if len(body) > cloudPATVerifyRequestMaxBytes {+ // Defense in depth: would only fire if a future change adds+ // expected_* fields and someone passes pathological input.+ return CloudPATIdentity{}, fmt.Errorf("%w: request body exceeds %d bytes", ErrCloudPATUnavailable, cloudPATVerifyRequestMaxBytes)+ }++ req, err := http.NewRequestWithContext(ctx, http.MethodPost, v.baseURL+cloudPATVerifyPath, bytes.NewReader(body))+ if err != nil {+ return CloudPATIdentity{}, fmt.Errorf("%w: build request: %v", ErrCloudPATUnavailable, err)+ }+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Accept", "application/json")++ resp, err := v.http.Do(req)+ if err != nil {+ // Network error / timeout / DNS / dial failure. We deliberately+ // don't expose `err.Error()` to the HTTP response — let the+ // middleware emit a generic 503. Local logs still see the+ // real cause via the slog at the call site.+ slog.Warn("cloud_pat: verify request failed", "error", err)+ return CloudPATIdentity{}, ErrCloudPATUnavailable+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {+ // Per the Cloud doc, 400 means our request was malformed and+ // 500 means Fleet itself is broken. Either way the right move+ // upstream is "treat the token as un-verifiable right now,+ // return 503". Read a small chunk of the body for log+ // context only.+ var snippet string+ if buf, _ := io.ReadAll(io.LimitReader(resp.Body, 512)); len(buf) > 0 {+ snippet = strings.TrimSpace(string(buf))+ }+ slog.Warn("cloud_pat: verify returned non-200", "status", resp.StatusCode, "body", snippet)+ return CloudPATIdentity{}, ErrCloudPATUnavailable+ }++ raw, err := io.ReadAll(io.LimitReader(resp.Body, cloudPATVerifyResponseMaxBytes+1))+ if err != nil {+ slog.Warn("cloud_pat: read response failed", "error", err)+ return CloudPATIdentity{}, ErrCloudPATUnavailable+ }+ if len(raw) > cloudPATVerifyResponseMaxBytes {+ slog.Warn("cloud_pat: verify response too large", "limit", cloudPATVerifyResponseMaxBytes)+ return CloudPATIdentity{}, ErrCloudPATUnavailable+ }++ var parsed fleetVerifyResponse+ if err := json.Unmarshal(raw, &parsed); err != nil {+ slog.Warn("cloud_pat: decode response failed", "error", err)+ return CloudPATIdentity{}, ErrCloudPATUnavailable+ }++ if !parsed.Valid {+ // Surface the reason in the error so the middleware can log+ // "why" while still returning a generic 401 to the client.+ return CloudPATIdentity{}, &CloudPATInvalidError{Reason: parsed.Reason}+ }++ if parsed.OwnerID == "" {+ // Defense against a Fleet response that claims valid:true+ // but omits owner_id — without owner_id we have nothing to+ // put in X-User-ID, so it's effectively unusable. Fail+ // closed rather than passing an empty user id downstream.+ slog.Warn("cloud_pat: verify returned valid=true with empty owner_id")+ return CloudPATIdentity{}, ErrCloudPATUnavailable+ }++ return CloudPATIdentity{+ OwnerID: parsed.OwnerID,+ InstanceID: parsed.InstanceID,+ InstanceRecordID: parsed.InstanceRecordID,+ }, nil+}++func cloudPATCacheKey(hash string) string { return cloudPATCachePrefix + hash }++func (v *CloudPATVerifier) cacheGet(ctx context.Context, hash string) (CloudPATIdentity, bool) {+ if v == nil || v.rdb == nil {+ return CloudPATIdentity{}, false+ }+ raw, err := v.rdb.Get(ctx, cloudPATCacheKey(hash)).Bytes()+ if err != nil {+ if !errors.Is(err, redis.Nil) {+ slog.Warn("cloud_pat: cache get failed; falling back to fleet", "error", err)+ }+ return CloudPATIdentity{}, false+ }+ var id CloudPATIdentity+ if err := json.Unmarshal(raw, &id); err != nil {+ slog.Warn("cloud_pat: cache entry malformed; falling back to fleet", "error", err)+ return CloudPATIdentity{}, false+ }+ if id.OwnerID == "" {+ // Safety net: a malformed cache entry (e.g. left over from a+ // prior schema) without an owner_id must not be treated as a+ // hit, otherwise the middleware would set X-User-ID to "".+ return CloudPATIdentity{}, false+ }+ return id, true+}++func (v *CloudPATVerifier) cacheSet(ctx context.Context, hash string, id CloudPATIdentity) {+ if v == nil || v.rdb == nil {+ return+ }+ raw, err := json.Marshal(id)+ if err != nil {+ slog.Warn("cloud_pat: cache marshal failed", "error", err)+ return+ }+ if err := v.rdb.Set(ctx, cloudPATCacheKey(hash), raw, cloudPATCacheTTL).Err(); err != nil {+ slog.Warn("cloud_pat: cache set failed", "error", err)+ }+}diff --git a/server/internal/auth/cloud_pat_test.go b/server/internal/auth/cloud_pat_test.gonew file mode 100644index 0000000000..ff1048b65e--- /dev/null+++ b/server/internal/auth/cloud_pat_test.go@@ -0,0 +1,461 @@+package auth++import (+ "context"+ "errors"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++// fleetServerOpts configures the stub Fleet server used in tests. Each+// field is optional — zero values give a default 200 success response+// with a fixed owner/instance binding.+type fleetServerOpts struct {+ statusCode int+ body string+ delay time.Duration+ // recordReqs is incremented on each verify call we receive, so a+ // test can assert "the cache short-circuits the HTTP layer" by+ // verifying this counter doesn't move on a cache hit.+ recordReqs *int32+ // expectToken, if non-empty, fails the test if the request body+ // does not contain this exact token plaintext.+ expectToken string+}++func newFleetServer(t *testing.T, opts fleetServerOpts) *httptest.Server {+ t.Helper()+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if opts.recordReqs != nil {+ atomic.AddInt32(opts.recordReqs, 1)+ }+ if r.Method != http.MethodPost {+ t.Errorf("expected POST, got %s", r.Method)+ }+ if r.URL.Path != "/api/v1/pat/verify" {+ t.Errorf("unexpected path: %s", r.URL.Path)+ }+ if opts.expectToken != "" {+ body, _ := io.ReadAll(r.Body)+ if !strings.Contains(string(body), opts.expectToken) {+ t.Errorf("request body missing expected token; got: %s", string(body))+ }+ }+ if opts.delay > 0 {+ time.Sleep(opts.delay)+ }+ status := opts.statusCode+ if status == 0 {+ status = http.StatusOK+ }+ body := opts.body+ if body == "" {+ body = `{+ "valid": true,+ "owner_id": "01972f7e-7e8d-77ef-a13d-1b0ce3e9c001",+ "instance_id": "i-0123456789abcdef0",+ "instance_record_id": "01972f7e-8a13-72a1-bbb0-0874ed4e8e67"+ }`+ }+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(status)+ _, _ = w.Write([]byte(body))+ }))+}++// TestCloudPATVerifier_NilSafe pins the nil-receiver contract: a server+// without MULTICA_CLOUD_FLEET_URL configured constructs nil here, and+// the middleware nil-checks before calling. Verify must still return a+// classifiable error so the middleware emits a deterministic 401 instead+// of a nil-deref panic.+func TestCloudPATVerifier_NilSafe(t *testing.T) {+ var v *CloudPATVerifier+ if v.Configured() {+ t.Fatal("nil verifier reported Configured()=true")+ }+ _, err := v.Verify(context.Background(), "mcn_anything", nil)+ if !errors.Is(err, ErrCloudPATNotConfigured) {+ t.Fatalf("expected ErrCloudPATNotConfigured, got %v", err)+ }+}++// TestCloudPATVerifier_EmptyURLReturnsNil confirms that an empty+// FleetBaseURL yields a nil verifier (not a verifier that explodes on+// first request). This is the explicit signal to the middleware that+// mcn_ is unsupported on this deployment.+func TestCloudPATVerifier_EmptyURLReturnsNil(t *testing.T) {+ if v := NewCloudPATVerifier(CloudPATVerifierConfig{FleetBaseURL: " "}); v != nil {+ t.Fatalf("expected nil for empty URL, got %#v", v)+ }+}++// TestCloudPATVerifier_VerifySuccess exercises the happy path: Fleet+// returns valid=true, the verifier surfaces owner_id / instance_id /+// instance_record_id verbatim. We don't run a Redis here, so the cache+// path is exercised separately in TestCloudPATVerifier_CacheHitSkipsHTTP.+func TestCloudPATVerifier_VerifySuccess(t *testing.T) {+ srv := newFleetServer(t, fleetServerOpts{expectToken: "mcn_test_token"})+ defer srv.Close()++ v := NewCloudPATVerifier(CloudPATVerifierConfig{FleetBaseURL: srv.URL})+ if v == nil {+ t.Fatal("verifier should not be nil")+ }+ id, err := v.Verify(context.Background(), "mcn_test_token", nil)+ if err != nil {+ t.Fatalf("Verify failed: %v", err)+ }+ if id.OwnerID != "01972f7e-7e8d-77ef-a13d-1b0ce3e9c001" {+ t.Errorf("unexpected owner_id: %q", id.OwnerID)+ }+ if id.InstanceID != "i-0123456789abcdef0" {+ t.Errorf("unexpected instance_id: %q", id.InstanceID)+ }+ if id.InstanceRecordID != "01972f7e-8a13-72a1-bbb0-0874ed4e8e67" {+ t.Errorf("unexpected instance_record_id: %q", id.InstanceRecordID)+ }+}++// TestCloudPATVerifier_VerifyEmptyToken pins an early-out: the middleware+// strips "Bearer " before calling Verify, so an empty plaintext is a+// programming error here, not a Fleet round-trip.+func TestCloudPATVerifier_VerifyEmptyToken(t *testing.T) {+ v := NewCloudPATVerifier(CloudPATVerifierConfig{FleetBaseURL: "http://example.invalid"})+ _, err := v.Verify(context.Background(), "", nil)+ if !errors.Is(err, ErrCloudPATInvalid) {+ t.Fatalf("expected ErrCloudPATInvalid, got %v", err)+ }+}++// TestCloudPATVerifier_InvalidReasons walks every documented reason+// for a valid=false response and confirms each maps onto+// CloudPATInvalidError + matches errors.Is(ErrCloudPATInvalid). The+// reason string itself is preserved on the typed error for logging.+func TestCloudPATVerifier_InvalidReasons(t *testing.T) {+ reasons := []string{+ "format_invalid",+ "checksum_invalid",+ "token_not_found",+ "token_revoked",+ "token_expired",+ "owner_mismatch",+ "instance_mismatch",+ }+ for _, reason := range reasons {+ t.Run(reason, func(t *testing.T) {+ body := `{"valid":false,"reason":"` + reason + `"}`+ srv := newFleetServer(t, fleetServerOpts{body: body})+ defer srv.Close()++ v := NewCloudPATVerifier(CloudPATVerifierConfig{FleetBaseURL: srv.URL})+ _, err := v.Verify(context.Background(), "mcn_x", nil)+ if !errors.Is(err, ErrCloudPATInvalid) {+ t.Fatalf("expected ErrCloudPATInvalid for reason %q, got %v", reason, err)+ }+ var typed *CloudPATInvalidError+ if !errors.As(err, &typed) {+ t.Fatalf("expected *CloudPATInvalidError, got %T", err)+ }+ if typed.Reason != reason {+ t.Errorf("expected Reason=%q, got %q", reason, typed.Reason)+ }+ })+ }+}++// TestCloudPATVerifier_FleetReturns500 — Fleet itself is broken. We+// must surface ErrCloudPATUnavailable so the middleware emits 503,+// not 401: a 401 here would tell a CLI/daemon to throw out a valid+// token because of a transient cloud outage.+func TestCloudPATVerifier_FleetReturns500(t *testing.T) {+ srv := newFleetServer(t, fleetServerOpts{statusCode: http.StatusInternalServerError, body: "boom"})+ defer srv.Close()++ v := NewCloudPATVerifier(CloudPATVerifierConfig{FleetBaseURL: srv.URL})+ _, err := v.Verify(context.Background(), "mcn_x", nil)+ if !errors.Is(err, ErrCloudPATUnavailable) {+ t.Fatalf("expected ErrCloudPATUnavailable for 500, got %v", err)+ }+}++// TestCloudPATVerifier_FleetReturns400 — a malformed-request 400 from+// Fleet still maps onto Unavailable, not Invalid: the token isn't+// known to be bad, *we* are talking to Fleet wrong. The middleware+// emits 503 and the token is retried on the next request.+func TestCloudPATVerifier_FleetReturns400(t *testing.T) {+ srv := newFleetServer(t, fleetServerOpts{statusCode: http.StatusBadRequest, body: `{"error":"bad"}`})+ defer srv.Close()++ v := NewCloudPATVerifier(CloudPATVerifierConfig{FleetBaseURL: srv.URL})+ _, err := v.Verify(context.Background(), "mcn_x", nil)+ if !errors.Is(err, ErrCloudPATUnavailable) {+ t.Fatalf("expected ErrCloudPATUnavailable for 400, got %v", err)+ }+}++// TestCloudPATVerifier_NetworkError — pointing at a closed port+// simulates DNS failure / connection refused. Same Unavailable mapping.+func TestCloudPATVerifier_NetworkError(t *testing.T) {+ // Bind a server then close it immediately to get a guaranteed-+ // unreachable URL on a free port.+ srv := newFleetServer(t, fleetServerOpts{})+ url := srv.URL+ srv.Close()++ v := NewCloudPATVerifier(CloudPATVerifierConfig{+ FleetBaseURL: url,+ HTTPClient: &http.Client{Timeout: 200 * time.Millisecond},+ })+ _, err := v.Verify(context.Background(), "mcn_x", nil)+ if !errors.Is(err, ErrCloudPATUnavailable) {+ t.Fatalf("expected ErrCloudPATUnavailable on network error, got %v", err)+ }+}++// TestCloudPATVerifier_ValidTrueWithoutOwnerIDFailsClosed pins the+// defense for a Fleet response that says valid=true but omits+// owner_id. Without an owner_id the middleware would set X-User-ID to+// "" and trick downstream handlers into thinking the request is+// authenticated as the empty user — fail closed instead.+func TestCloudPATVerifier_ValidTrueWithoutOwnerIDFailsClosed(t *testing.T) {+ srv := newFleetServer(t, fleetServerOpts{body: `{"valid":true}`})+ defer srv.Close()++ v := NewCloudPATVerifier(CloudPATVerifierConfig{FleetBaseURL: srv.URL})+ _, err := v.Verify(context.Background(), "mcn_x", nil)+ if !errors.Is(err, ErrCloudPATUnavailable) {+ t.Fatalf("expected ErrCloudPATUnavailable for valid:true without owner_id, got %v", err)+ }+}++// TestCloudPATVerifier_DecodeError exercises the case where Fleet+// returns 200 but with garbage that won't decode as JSON. Treated as+// Unavailable — same logic as a 5xx.+func TestCloudPATVerifier_DecodeError(t *testing.T) {+ srv := newFleetServer(t, fleetServerOpts{body: "<not json>"})+ defer srv.Close()++ v := NewCloudPATVerifier(CloudPATVerifierConfig{FleetBaseURL: srv.URL})+ _, err := v.Verify(context.Background(), "mcn_x", nil)+ if !errors.Is(err, ErrCloudPATUnavailable) {+ t.Fatalf("expected ErrCloudPATUnavailable for decode error, got %v", err)+ }+}++// TestCloudPATVerifier_ContextCanceled confirms that request+// cancellation propagates as Unavailable. A canceled request is+// indistinguishable from a network failure at the auth-result level.+func TestCloudPATVerifier_ContextCanceled(t *testing.T) {+ srv := newFleetServer(t, fleetServerOpts{delay: 200 * time.Millisecond})+ defer srv.Close()++ v := NewCloudPATVerifier(CloudPATVerifierConfig{FleetBaseURL: srv.URL})++ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ _, err := v.Verify(ctx, "mcn_x", nil)+ if !errors.Is(err, ErrCloudPATUnavailable) {+ t.Fatalf("expected ErrCloudPATUnavailable on canceled ctx, got %v", err)+ }+}++// TestCloudPATVerifier_TrimsTrailingSlash is a tiny sanity test —+// configurations sometimes carry trailing slashes; the verifier must+// normalize so it doesn't double-slash the verify path. (httptest's+// router would still accept it, but the actual Fleet won't.)+func TestCloudPATVerifier_TrimsTrailingSlash(t *testing.T) {+ srv := newFleetServer(t, fleetServerOpts{})+ defer srv.Close()++ v := NewCloudPATVerifier(CloudPATVerifierConfig{FleetBaseURL: srv.URL + "/"})+ if v == nil {+ t.Fatal("verifier should not be nil")+ }+ if _, err := v.Verify(context.Background(), "mcn_x", nil); err != nil {+ t.Fatalf("Verify with trailing-slash baseURL failed: %v", err)+ }+}++// TestCloudPATVerifier_CacheHitSkipsHTTP confirms the Redis cache+// short-circuits the Fleet round-trip. After one successful Verify the+// next call must not increment the request counter — that's the entire+// point of the cache layer (one Fleet hit per cloudPATCacheTTL window+// per token, regardless of request rate).+func TestCloudPATVerifier_CacheHitSkipsHTTP(t *testing.T) {+ rdb := newRedisTestClient(t)++ var calls int32+ srv := newFleetServer(t, fleetServerOpts{recordReqs: &calls})+ defer srv.Close()++ v := NewCloudPATVerifier(CloudPATVerifierConfig{FleetBaseURL: srv.URL, Redis: rdb})++ first, err := v.Verify(context.Background(), "mcn_repeat", nil)+ if err != nil {+ t.Fatalf("first Verify failed: %v", err)+ }+ if first.OwnerID == "" {+ t.Fatal("first Verify returned empty owner_id")+ }++ second, err := v.Verify(context.Background(), "mcn_repeat", nil)+ if err != nil {+ t.Fatalf("second Verify failed: %v", err)+ }+ if second != first {+ t.Fatalf("cache returned different identity: first=%+v second=%+v", first, second)+ }+ if got := atomic.LoadInt32(&calls); got != 1 {+ t.Fatalf("expected 1 fleet call, got %d", got)+ }+}++// TestCloudPATVerifier_NegativesNotCached pins the explicit choice from+// the Cloud doc: "revoke / expired / mismatch results MUST NOT be+// cached". A token that flips back to valid (lazy-revoke+// reconciliation, owner_id updated, etc.) needs to start working again+// without waiting for a TTL window.+func TestCloudPATVerifier_NegativesNotCached(t *testing.T) {+ rdb := newRedisTestClient(t)++ var calls int32+ srv := newFleetServer(t, fleetServerOpts{+ body: `{"valid":false,"reason":"token_revoked"}`,+ recordReqs: &calls,+ })+ defer srv.Close()++ v := NewCloudPATVerifier(CloudPATVerifierConfig{FleetBaseURL: srv.URL, Redis: rdb})++ _, err := v.Verify(context.Background(), "mcn_revoked", nil)+ if !errors.Is(err, ErrCloudPATInvalid) {+ t.Fatalf("first Verify: expected invalid, got %v", err)+ }+ _, err = v.Verify(context.Background(), "mcn_revoked", nil)+ if !errors.Is(err, ErrCloudPATInvalid) {+ t.Fatalf("second Verify: expected invalid, got %v", err)+ }+ if got := atomic.LoadInt32(&calls); got != 2 {+ t.Fatalf("negative result must not be cached; expected 2 fleet calls, got %d", got)+ }+}+++// TestCloudPATVerifier_LookupRejectsUnknownOwner pins the new+// owner-existence guard. Cloud says the token is valid, but the+// caller's lookup says the owner_id does not exist locally — the+// verifier must reject with reason="owner_unknown" and MUST NOT+// cache the result, so a freshly-created user can authenticate+// immediately on the next call without waiting for a TTL.+func TestCloudPATVerifier_LookupRejectsUnknownOwner(t *testing.T) {+ rdb := newRedisTestClient(t)++ var calls int32+ srv := newFleetServer(t, fleetServerOpts{recordReqs: &calls})+ defer srv.Close()++ v := NewCloudPATVerifier(CloudPATVerifierConfig{FleetBaseURL: srv.URL, Redis: rdb})++ lookup := func(_ context.Context, ownerID string) (bool, error) {+ // Cloud's stub returns this fixed owner_id; assert we receive+ // it before reporting "not found" so a future regression that+ // passes the wrong field would surface here.+ if ownerID != "01972f7e-7e8d-77ef-a13d-1b0ce3e9c001" {+ t.Errorf("lookup called with unexpected owner_id: %q", ownerID)+ }+ return false, nil+ }++ first, err := v.Verify(context.Background(), "mcn_unknown_owner", lookup)+ if !errors.Is(err, ErrCloudPATInvalid) {+ t.Fatalf("expected ErrCloudPATInvalid, got %v (id=%+v)", err, first)+ }+ var typed *CloudPATInvalidError+ if !errors.As(err, &typed) {+ t.Fatalf("expected *CloudPATInvalidError, got %T", err)+ }+ if typed.Reason != CloudPATInvalidReasonOwnerUnknown {+ t.Errorf("expected reason=%q, got %q", CloudPATInvalidReasonOwnerUnknown, typed.Reason)+ }++ // Second call: lookup now says the user exists. If the previous+ // rejection was cached, we'd still be rejected without the lookup+ // being consulted again. We must re-hit Fleet AND the lookup, and+ // succeed.+ gotLookup := false+ lookupExists := func(_ context.Context, _ string) (bool, error) {+ gotLookup = true+ return true, nil+ }+ id, err := v.Verify(context.Background(), "mcn_unknown_owner", lookupExists)+ if err != nil {+ t.Fatalf("second Verify failed: %v", err)+ }+ if id.OwnerID == "" {+ t.Fatal("second Verify returned empty owner_id")+ }+ if !gotLookup {+ t.Fatal("second Verify did not consult the lookup — owner_unknown was wrongly cached")+ }+ if got := atomic.LoadInt32(&calls); got != 2 {+ t.Fatalf("owner_unknown must not be cached; expected 2 fleet calls, got %d", got)+ }+}++// TestCloudPATVerifier_LookupErrorMapsToUnavailable confirms that an+// infrastructure error from the lookup (DB down, query timeout, ...)+// surfaces as ErrCloudPATUnavailable so the middleware emits 503,+// not 401. Without this, a transient DB blip would tell every CLI+// and daemon to throw out a still-valid token.+func TestCloudPATVerifier_LookupErrorMapsToUnavailable(t *testing.T) {+ srv := newFleetServer(t, fleetServerOpts{})+ defer srv.Close()++ v := NewCloudPATVerifier(CloudPATVerifierConfig{FleetBaseURL: srv.URL})++ lookup := func(_ context.Context, _ string) (bool, error) {+ return false, errors.New("db is down")+ }+ _, err := v.Verify(context.Background(), "mcn_db_blip", lookup)+ if !errors.Is(err, ErrCloudPATUnavailable) {+ t.Fatalf("expected ErrCloudPATUnavailable, got %v", err)+ }+}++// TestCloudPATVerifier_LookupSuccessIsCached confirms that a verified+// + locally-existing owner_id IS cached: the second Verify must not+// hit Fleet OR the lookup. This is the happy-path symmetry to the+// previous two tests.+func TestCloudPATVerifier_LookupSuccessIsCached(t *testing.T) {+ rdb := newRedisTestClient(t)++ var fleetCalls int32+ srv := newFleetServer(t, fleetServerOpts{recordReqs: &fleetCalls})+ defer srv.Close()++ v := NewCloudPATVerifier(CloudPATVerifierConfig{FleetBaseURL: srv.URL, Redis: rdb})++ var lookupCalls int32+ lookup := func(_ context.Context, _ string) (bool, error) {+ atomic.AddInt32(&lookupCalls, 1)+ return true, nil+ }++ if _, err := v.Verify(context.Background(), "mcn_cacheable", lookup); err != nil {+ t.Fatalf("first Verify failed: %v", err)+ }+ if _, err := v.Verify(context.Background(), "mcn_cacheable", lookup); err != nil {+ t.Fatalf("second Verify failed: %v", err)+ }+ if got := atomic.LoadInt32(&fleetCalls); got != 1 {+ t.Fatalf("expected 1 fleet call (second hits cache), got %d", got)+ }+ if got := atomic.LoadInt32(&lookupCalls); got != 1 {+ t.Fatalf("expected 1 lookup call (second hits cache), got %d", got)+ }+}diff --git a/server/internal/cloudruntime/client.go b/server/internal/cloudruntime/client.goindex ab5490f59d..b4959ba83e 100644--- a/server/internal/cloudruntime/client.go+++ b/server/internal/cloudruntime/client.go@@ -34,7 +34,6 @@ type Request struct {Query url.ValuesBody []byteUserID string- UserPAT stringRequestID string}@@ -100,9 +99,6 @@ func (c *Client) Do(ctx context.Context, req Request) (*Response, error) {if req.UserID != "" {httpReq.Header.Set("X-User-ID", req.UserID)}- if req.UserPAT != "" {- httpReq.Header.Set("X-User-PAT", req.UserPAT)- }if req.RequestID != "" {httpReq.Header.Set("X-Request-ID", req.RequestID)}diff --git a/server/internal/cloudruntime/client_test.go b/server/internal/cloudruntime/client_test.goindex 96b42e7aa6..a99d4a22a2 100644--- a/server/internal/cloudruntime/client_test.go+++ b/server/internal/cloudruntime/client_test.go@@ -30,9 +30,6 @@ func TestClientDoForwardsFleetRequest(t *testing.T) {if got := r.Header.Get("X-User-ID"); got != "01972f7e-7e8d-77ef-a13d-1b0ce3e9c001" {t.Fatalf("X-User-ID = %q", got)}- if got := r.Header.Get("X-User-PAT"); got != "mul_test_pat" {- t.Fatalf("X-User-PAT = %q", got)- }if got := r.Header.Get("X-Request-ID"); got != "request-123" {t.Fatalf("X-Request-ID = %q", got)}@@ -56,7 +53,6 @@ func TestClientDoForwardsFleetRequest(t *testing.T) {Query: url.Values{"limit": []string{"20"}, "offset": []string{"0"}},Body: []byte(`{"instance_type":"g5.xlarge"}`),UserID: "01972f7e-7e8d-77ef-a13d-1b0ce3e9c001",- UserPAT: "mul_test_pat",RequestID: "request-123",})if err != nil {diff --git a/server/internal/handler/cloud_runtime.go b/server/internal/handler/cloud_runtime.goindex 2020608cd1..2b39a04d1d 100644--- a/server/internal/handler/cloud_runtime.go+++ b/server/internal/handler/cloud_runtime.go@@ -9,23 +9,18 @@ import ("log/slog""net/http""net/url"- "strings"- "time"chimw "github.com/go-chi/chi/v5/middleware"- "github.com/multica-ai/multica/server/internal/auth""github.com/multica-ai/multica/server/internal/cloudruntime""github.com/multica-ai/multica/server/internal/logger"- db "github.com/multica-ai/multica/server/pkg/db/generated")const maxCloudRuntimeRequestBodySize = 1 << 20type cloudRuntimeProxyOptions struct {- withUserID bool- withQuery bool- withBody bool- withUserPAT bool+ withUserID bool+ withQuery bool+ withBody bool}func (h *Handler) GetCloudRuntimeService(w http.ResponseWriter, r *http.Request) {@@ -50,10 +45,16 @@ func (h *Handler) ListCloudRuntimeNodes(w http.ResponseWriter, r *http.Request)}func (h *Handler) CreateCloudRuntimeNode(w http.ResponseWriter, r *http.Request) {+ // Cloud now mints a node-scoped mcn_ PAT itself during /api/v1/nodes+ // and injects it into the EC2 instance via SSM bootstrap (see+ // multica-cloud docs/api/node-pat.md). We no longer forward the+ // caller's mul_ PAT — Fleet doesn't need it, and propagating a+ // long-lived user PAT into a remote machine widened the blast+ // radius of any node compromise. Hence the handler now mirrors+ // the other write endpoints: just the body, no PAT plumbing.h.proxyCloudRuntime(w, r, http.MethodPost, "/api/v1/nodes", cloudRuntimeProxyOptions{- withUserID: true,- withBody: true,- withUserPAT: true,+ withUserID: true,+ withBody: true,})}@@ -123,11 +124,6 @@ func (h *Handler) proxyCloudRuntime(w http.ResponseWriter, r *http.Request, meth}}- userPAT, patGenerated, ok := h.cloudRuntimeUserPAT(w, r, userID, opts.withUserPAT)- if !ok {- return- }-var query url.Valuesif opts.withQuery {query = r.URL.Query()@@ -139,19 +135,12 @@ func (h *Handler) proxyCloudRuntime(w http.ResponseWriter, r *http.Request, methQuery: query,Body: body,UserID: userID,- UserPAT: userPAT,RequestID: cloudRuntimeRequestID(r),})if err != nil {- if patGenerated {- h.revokeGeneratedPAT(r.Context(), userPAT)- }writeCloudRuntimeError(w, r, err)return}- if patGenerated && resp.StatusCode >= 300 {- h.revokeGeneratedPAT(r.Context(), userPAT)- }writeCloudRuntimeResponse(w, resp)}@@ -186,71 +175,6 @@ func cloudRuntimeRequestID(r *http.Request) string {return chimw.GetReqID(r.Context())}-func (h *Handler) cloudRuntimeUserPAT(w http.ResponseWriter, r *http.Request, userID string, enabled bool) (pat string, generated bool, ok bool) {- if !enabled {- return "", false, true- }- if p := strings.TrimSpace(r.Header.Get("X-User-PAT")); p != "" {- if !strings.HasPrefix(p, "mul_") {- writeError(w, http.StatusBadRequest, "invalid X-User-PAT")- return "", false, false- }- if h.Queries == nil {- writeError(w, http.StatusInternalServerError, "failed to validate X-User-PAT")- return "", false, false- }- token, err := h.Queries.GetPersonalAccessTokenByHash(r.Context(), auth.HashToken(p))- if err != nil || uuidToString(token.UserID) != userID {- writeError(w, http.StatusForbidden, "invalid X-User-PAT")- return "", false, false- }- return p, false, true- }-- authHeader := strings.TrimSpace(r.Header.Get("Authorization"))- const prefix = "Bearer "- if strings.HasPrefix(authHeader, prefix+"mul_") {- return strings.TrimPrefix(authHeader, prefix), false, true- }-- // Auto-generate a PAT for cloud runtime bootstrap.- p, err := h.generateCloudRuntimePAT(r.Context(), userID)- if err != nil {- slog.Error("failed to generate cloud runtime PAT", append(logger.RequestAttrs(r), "error", err)...)- writeError(w, http.StatusInternalServerError, "failed to generate cloud runtime PAT")- return "", false, false- }- return p, true, true-}--func (h *Handler) generateCloudRuntimePAT(ctx context.Context, userID string) (string, error) {- rawToken, err := auth.GeneratePATToken()- if err != nil {- return "", err- }- prefix := rawToken[:12]- _, err = h.Queries.CreatePersonalAccessToken(ctx, db.CreatePersonalAccessTokenParams{- UserID: parseUUID(userID),- Name: "Cloud Runtime (auto)",- TokenHash: auth.HashToken(rawToken),- TokenPrefix: prefix,- })- if err != nil {- return "", err- }- return rawToken, nil-}--func (h *Handler) revokeGeneratedPAT(ctx context.Context, rawToken string) {- ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)- defer cancel()- hash := auth.HashToken(rawToken)- if _, err := h.DB.Exec(ctx, `UPDATE personal_access_token SET revoked = TRUE WHERE token_hash = $1`, hash); err != nil {- slog.Warn("failed to revoke auto-generated cloud runtime PAT", "error", err)- }- h.PATCache.Invalidate(ctx, hash)-}-func writeCloudRuntimeResponse(w http.ResponseWriter, resp *cloudruntime.Response) {if requestID := resp.Header.Get("X-Request-ID"); requestID != "" {w.Header().Set("X-Request-ID", requestID)diff --git a/server/internal/handler/cloud_runtime_test.go b/server/internal/handler/cloud_runtime_test.goindex 8a80c242c0..3ae831c59e 100644--- a/server/internal/handler/cloud_runtime_test.go+++ b/server/internal/handler/cloud_runtime_test.go@@ -7,12 +7,8 @@ import ("net/http/httptest""strings""testing"- "time"- "github.com/jackc/pgx/v5/pgtype"- "github.com/multica-ai/multica/server/internal/auth""github.com/multica-ai/multica/server/internal/cloudruntime"- db "github.com/multica-ai/multica/server/pkg/db/generated")type fakeCloudRuntimeProxy struct {@@ -44,22 +40,13 @@ func useCloudRuntimeProxy(t *testing.T, proxy cloudRuntimeProxy) {t.Cleanup(func() { testHandler.CloudRuntime = prevProxy })}-func TestCreateCloudRuntimeNodeForwardsValidatedPAT(t *testing.T) {- rawPAT := "mul_cloud_runtime_test_valid_pat"- _, err := testHandler.Queries.CreatePersonalAccessToken(context.Background(), db.CreatePersonalAccessTokenParams{- UserID: parseUUID(testUserID),- Name: "cloud runtime test",- TokenHash: auth.HashToken(rawPAT),- TokenPrefix: rawPAT[:12],- ExpiresAt: pgtype.Timestamptz{},- })- if err != nil {- t.Fatalf("create PAT: %v", err)- }- t.Cleanup(func() {- _, _ = testPool.Exec(context.Background(), `DELETE FROM personal_access_token WHERE token_hash = $1`, auth.HashToken(rawPAT))- })-+// TestCreateCloudRuntimeNodeForwardsBody is the post-MUL-2671 happy+// path for CreateCloudRuntimeNode: the handler no longer reads, asks+// for, or auto-generates an mul_ PAT — Cloud now mints its own+// node-scoped mcn_ PAT during /api/v1/nodes and ships it to the EC2+// instance via SSM. Multica-api just forwards the request body and+// the caller's user_id; there is no PAT plumbing on this endpoint.+func TestCreateCloudRuntimeNodeForwardsBody(t *testing.T) {proxy := &fakeCloudRuntimeProxy{enabled: true,resp: &cloudruntime.Response{@@ -73,7 +60,6 @@ func TestCreateCloudRuntimeNodeForwardsValidatedPAT(t *testing.T) {req := newRequest(http.MethodPost, "/api/cloud-runtime/nodes", map[string]any{"instance_type": "g5.xlarge",})- req.Header.Set("X-User-PAT", rawPAT)req.Header.Set("X-Request-ID", "api-request-id")w := httptest.NewRecorder()@@ -91,9 +77,6 @@ func TestCreateCloudRuntimeNodeForwardsValidatedPAT(t *testing.T) {if proxy.req.UserID != testUserID {t.Fatalf("proxied user id = %q", proxy.req.UserID)}- if proxy.req.UserPAT != rawPAT {- t.Fatalf("proxied PAT = %q", proxy.req.UserPAT)- }if proxy.req.RequestID != "api-request-id" {t.Fatalf("proxied request id = %q", proxy.req.RequestID)}@@ -102,105 +85,6 @@ func TestCreateCloudRuntimeNodeForwardsValidatedPAT(t *testing.T) {}}-func TestCreateCloudRuntimeNodeRejectsUnownedPAT(t *testing.T) {- proxy := &fakeCloudRuntimeProxy{- enabled: true,- resp: &cloudruntime.Response{- StatusCode: http.StatusCreated,- Body: []byte(`{"status":"launching"}`),- },- }- useCloudRuntimeProxy(t, proxy)-- req := newRequest(http.MethodPost, "/api/cloud-runtime/nodes", map[string]any{- "instance_type": "g5.xlarge",- })- req.Header.Set("X-User-PAT", "mul_cloud_runtime_test_missing_pat")- w := httptest.NewRecorder()-- testHandler.CreateCloudRuntimeNode(w, req)-- if w.Code != http.StatusForbidden {- t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())- }- if proxy.called {- t.Fatal("cloud runtime proxy should not be called")- }-}--func TestCreateCloudRuntimeNodeRejectsExpiredPAT(t *testing.T) {- rawPAT := "mul_cloud_runtime_test_expired_pat"- _, err := testHandler.Queries.CreatePersonalAccessToken(context.Background(), db.CreatePersonalAccessTokenParams{- UserID: parseUUID(testUserID),- Name: "cloud runtime expired test",- TokenHash: auth.HashToken(rawPAT),- TokenPrefix: rawPAT[:12],- ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(-time.Hour), Valid: true},- })- if err != nil {- t.Fatalf("create PAT: %v", err)- }- t.Cleanup(func() {- _, _ = testPool.Exec(context.Background(), `DELETE FROM personal_access_token WHERE token_hash = $1`, auth.HashToken(rawPAT))- })-- proxy := &fakeCloudRuntimeProxy{- enabled: true,- resp: &cloudruntime.Response{- StatusCode: http.StatusCreated,- Body: []byte(`{"status":"launching"}`),- },- }- useCloudRuntimeProxy(t, proxy)-- req := newRequest(http.MethodPost, "/api/cloud-runtime/nodes", map[string]any{- "instance_type": "g5.xlarge",- })- req.Header.Set("X-User-PAT", rawPAT)- w := httptest.NewRecorder()-- testHandler.CreateCloudRuntimeNode(w, req)-- if w.Code != http.StatusForbidden {- t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())- }- if proxy.called {- t.Fatal("cloud runtime proxy should not be called")- }-}--func TestCreateCloudRuntimeNodeAutoGeneratesPAT(t *testing.T) {- proxy := &fakeCloudRuntimeProxy{- enabled: true,- resp: &cloudruntime.Response{- StatusCode: http.StatusCreated,- Header: http.Header{},- Body: []byte(`{"status":"launching"}`),- },- }- useCloudRuntimeProxy(t, proxy)-- req := newRequest(http.MethodPost, "/api/cloud-runtime/nodes", map[string]any{- "instance_type": "g5.xlarge",- })- // No X-User-PAT header set — should auto-generate.- w := httptest.NewRecorder()-- testHandler.CreateCloudRuntimeNode(w, req)-- if w.Code != http.StatusCreated {- t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())- }- if !proxy.called {- t.Fatal("cloud runtime proxy was not called")- }- if !strings.HasPrefix(proxy.req.UserPAT, "mul_") {- t.Fatalf("expected auto-generated PAT with mul_ prefix, got %q", proxy.req.UserPAT)- }- // Clean up the auto-generated PAT.- _, _ = testPool.Exec(context.Background(), `DELETE FROM personal_access_token WHERE token_hash = $1`, auth.HashToken(proxy.req.UserPAT))-}-func TestCloudRuntimeDisabledReturnsUnavailable(t *testing.T) {useCloudRuntimeProxy(t, &fakeCloudRuntimeProxy{enabled: false})diff --git a/server/internal/middleware/auth.go b/server/internal/middleware/auth.goindex 38146c3486..1ae9a5b06a 100644--- a/server/internal/middleware/auth.go+++ b/server/internal/middleware/auth.go@@ -2,6 +2,7 @@ package middlewareimport ("context"+ "errors""log/slog""net/http""strings"@@ -27,7 +28,13 @@ func uuidToString(u pgtype.UUID) string { return util.UUIDToString(u) }// TTL (auth.AuthCacheTTL). On cache hit the middleware skips both the DB// SELECT and the last_used_at UPDATE — last_used_at is therefore refreshed// at most once per TTL window per token, not per request.-func Auth(queries *db.Queries, patCache *auth.PATCache) func(http.Handler) http.Handler {+//+// cloudPAT is optional; when non-nil, tokens with the mcn_ prefix are+// validated by calling the Multica Cloud Fleet service rather than the+// local DB. When nil (Fleet URL unset) mcn_ tokens are rejected at the+// prefix branch — we don't fall through to the mul_ / JWT paths, since+// an mcn_ string is by construction not a valid mul_ PAT or JWT.+func Auth(queries *db.Queries, patCache *auth.PATCache, cloudPAT *auth.CloudPATVerifier) func(http.Handler) http.Handler {return func(next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {// X-Actor-Source is server-set only — any value supplied by@@ -89,6 +96,51 @@ func Auth(queries *db.Queries, patCache *auth.PATCache) func(http.Handler) http.return}+ // Cloud Node PAT: "mcn_" prefix. Verified by calling the+ // Multica Cloud Fleet service — Cloud (not us) is the+ // authoritative owner of the token's status and owner_id+ // binding. We never look at the local+ // personal_access_tokens table for this prefix; an mcn_+ // string is not a valid mul_ value, so falling through+ // would just be a redundant DB miss. When the verifier+ // is unconfigured (no MULTICA_CLOUD_FLEET_URL) we reject+ // at this branch rather than treating the token as a+ // JWT/PAT — failing closed avoids a misconfigured prod+ // silently downgrading auth.+ //+ // After Cloud confirms the token, we also confirm that+ // the returned owner_id maps to a real local user. The+ // Cloud `owner_id` and our `users.id` share the same UUID+ // space by contract, so this is a defense in depth: a+ // missing user means the local row was deleted out from+ // under a still-active node, or something is forging+ // owner_ids — either way we must not let the request+ // pass with a phantom X-User-ID.+ if strings.HasPrefix(tokenString, auth.CloudPATPrefix) {+ if cloudPAT == nil {+ slog.Warn("auth: mcn_ token presented but cloud verifier not configured", "path", r.URL.Path)+ http.Error(w, `{"error":"invalid token"}`, http.StatusUnauthorized)+ return+ }+ identity, err := cloudPAT.Verify(r.Context(), tokenString, ownerLookupFor(queries))+ if err != nil {+ if errors.Is(err, auth.ErrCloudPATInvalid) {+ slog.Warn("auth: cloud rejected mcn_ token", "path", r.URL.Path, "error", err)+ http.Error(w, `{"error":"invalid token"}`, http.StatusUnauthorized)+ return+ }+ // Cloud unreachable / 5xx / decode error. We surface+ // 503 so callers (CLI / daemon) can retry — a 401+ // here would tell them to throw out a valid token.+ slog.Warn("auth: cloud pat verify unavailable", "path", r.URL.Path, "error", err)+ http.Error(w, `{"error":"cloud pat verifier unavailable"}`, http.StatusServiceUnavailable)+ return+ }+ r.Header.Set("X-User-ID", identity.OwnerID)+ next.ServeHTTP(w, r)+ return+ }+// PAT: tokens starting with "mul_"if strings.HasPrefix(tokenString, "mul_") {hash := auth.HashToken(tokenString)diff --git a/server/internal/middleware/auth_test.go b/server/internal/middleware/auth_test.goindex a755f666de..6d637618d4 100644--- a/server/internal/middleware/auth_test.go+++ b/server/internal/middleware/auth_test.go@@ -57,7 +57,7 @@ func validClaims() jwt.MapClaims {// authMiddleware returns the Auth middleware with nil queries (JWT-only tests).func authMiddleware(next http.Handler) http.Handler {- return Auth(nil, nil)(next)+ return Auth(nil, nil, nil)(next)}func TestAuth_MissingHeader(t *testing.T) {@@ -237,7 +237,7 @@ func TestAuth_InvalidPAT(t *testing.T) {// boundary MUL-2600 introduces.func TestAuth_StripsClientSuppliedActorSource(t *testing.T) {var gotActorSource string- mw := Auth(nil, nil)+ mw := Auth(nil, nil, nil)handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {gotActorSource = r.Header.Get("X-Actor-Source")w.WriteHeader(http.StatusOK)@@ -280,7 +280,7 @@ func TestAuth_PATCacheHit(t *testing.T) {cache.Set(context.Background(), hash, "cached-user-id", auth.AuthCacheTTL)var gotUserID string- mw := Auth(nil, cache) // nil queries — only safe on cache hit+ mw := Auth(nil, cache, nil) // nil queries — only safe on cache hithandler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {gotUserID = r.Header.Get("X-User-ID")w.WriteHeader(http.StatusOK)@@ -298,3 +298,107 @@ func TestAuth_PATCacheHit(t *testing.T) {t.Fatalf("expected cached X-User-ID, got %q", gotUserID)}}+++// TestAuth_MCN_NoVerifierConfigured pins the same fail-closed branch+// as the daemon side: with no MULTICA_CLOUD_FLEET_URL configured, an+// mcn_ bearer token must be rejected with 401 at the prefix branch.+// We don't fall through — an mcn_ string can't be a valid mul_ PAT or+// JWT, so any fall-through would be wasted work.+func TestAuth_MCN_NoVerifierConfigured(t *testing.T) {+ mw := Auth(nil, nil, nil)+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ t.Fatal("next must not be called when verifier is unconfigured")+ }))+ req := httptest.NewRequest("GET", "/api/me", nil)+ req.Header.Set("Authorization", "Bearer mcn_anything")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)+ if w.Code != http.StatusUnauthorized {+ t.Fatalf("expected 401, got %d", w.Code)+ }+}++// TestAuth_MCN_ValidTokenSetsUserID is the happy-path mirror of the+// daemon test: a successful Fleet verify must surface owner_id as+// X-User-ID for downstream user-scoped handlers.+func TestAuth_MCN_ValidTokenSetsUserID(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{+ "valid": true,+ "owner_id": "01972f7e-7e8d-77ef-a13d-1b0ce3e9c001"+ }`))+ }))+ defer srv.Close()++ verifier := auth.NewCloudPATVerifier(auth.CloudPATVerifierConfig{FleetBaseURL: srv.URL})++ var gotUser string+ mw := Auth(nil, nil, verifier)+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotUser = r.Header.Get("X-User-ID")+ w.WriteHeader(http.StatusOK)+ }))++ req := httptest.NewRequest("GET", "/api/me", nil)+ req.Header.Set("Authorization", "Bearer mcn_x")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if gotUser != "01972f7e-7e8d-77ef-a13d-1b0ce3e9c001" {+ t.Errorf("expected owner_id propagated as X-User-ID, got %q", gotUser)+ }+}++// TestAuth_MCN_InvalidReturns401 confirms that a Fleet valid:false maps+// to 401 — the token is genuinely bad, retrying won't help.+func TestAuth_MCN_InvalidReturns401(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"valid":false,"reason":"token_revoked"}`))+ }))+ defer srv.Close()++ verifier := auth.NewCloudPATVerifier(auth.CloudPATVerifierConfig{FleetBaseURL: srv.URL})+ mw := Auth(nil, nil, verifier)+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ t.Fatal("next must not be called when token is invalid")+ }))++ req := httptest.NewRequest("GET", "/api/me", nil)+ req.Header.Set("Authorization", "Bearer mcn_revoked")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if w.Code != http.StatusUnauthorized {+ t.Fatalf("expected 401, got %d", w.Code)+ }+}++// TestAuth_MCN_FleetUnreachableReturns503 — the Unavailable branch must+// emit 503 (transient), distinguishing it from a 401 (token is bad).+func TestAuth_MCN_FleetUnreachableReturns503(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusInternalServerError)+ }))+ defer srv.Close()++ verifier := auth.NewCloudPATVerifier(auth.CloudPATVerifierConfig{FleetBaseURL: srv.URL})+ mw := Auth(nil, nil, verifier)+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ t.Fatal("next must not be called when fleet is unavailable")+ }))++ req := httptest.NewRequest("GET", "/api/me", nil)+ req.Header.Set("Authorization", "Bearer mcn_x")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if w.Code != http.StatusServiceUnavailable {+ t.Fatalf("expected 503, got %d", w.Code)+ }+}diff --git a/server/internal/middleware/daemon_auth.go b/server/internal/middleware/daemon_auth.goindex de6bd79bc7..a8c60ad46d 100644--- a/server/internal/middleware/daemon_auth.go+++ b/server/internal/middleware/daemon_auth.go@@ -2,6 +2,7 @@ package middlewareimport ("context"+ "errors""log/slog""net/http""strings"@@ -25,6 +26,7 @@ const (const (DaemonAuthPathDaemonToken = "daemon_token"DaemonAuthPathPAT = "pat"+ DaemonAuthPathCloudPAT = "cloud_pat"DaemonAuthPathJWT = "jwt")@@ -41,8 +43,8 @@ func DaemonIDFromContext(ctx context.Context) string {}// DaemonAuthPathFromContext returns which token kind authenticated this-// request — "daemon_token", "pat", or "jwt" — for telemetry. Empty when the-// request did not pass through DaemonAuth.+// request — "daemon_token", "pat", "cloud_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@@ -68,8 +70,13 @@ func WithDaemonContext(ctx context.Context, workspaceID, daemonID string) contex// regular Auth middleware, so a single hot PAT used by both human CLI// and a daemon converges on one DB round-trip per AuthCacheTTL window.//+// cloudPAT is optional; when non-nil, tokens with the mcn_ prefix are+// validated by calling the Multica Cloud Fleet service (X-User-ID gets the+// returned owner_id). When nil, mcn_ tokens are rejected at the prefix+// branch — same fail-closed contract as the regular Auth middleware.+//// Cache misses fall back to the original DB-backed behavior.-func DaemonAuth(queries *db.Queries, patCache *auth.PATCache, daemonCache *auth.DaemonTokenCache) func(http.Handler) http.Handler {+func DaemonAuth(queries *db.Queries, patCache *auth.PATCache, daemonCache *auth.DaemonTokenCache, cloudPAT *auth.CloudPATVerifier) 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")@@ -128,6 +135,37 @@ func DaemonAuth(queries *db.Queries, patCache *auth.PATCache, daemonCache *auth.return}+ // Cloud Node PAT: "mcn_" prefix. Mirrors the mcn_ branch+ // in Auth — Multica Cloud Fleet is authoritative, we only+ // surface the resolved owner_id as X-User-ID for the+ // downstream daemon handlers (which then check workspace+ // membership the usual way). Same fail-closed semantics:+ // no Fleet URL configured → 401, Fleet unreachable → 503.+ // We additionally require the owner_id to map to a real+ // local user — see the Auth comment for the rationale.+ if strings.HasPrefix(tokenString, auth.CloudPATPrefix) {+ if cloudPAT == nil {+ slog.Warn("daemon_auth: mcn_ token presented but cloud verifier not configured", "path", r.URL.Path)+ writeError(w, http.StatusUnauthorized, "invalid token")+ return+ }+ identity, err := cloudPAT.Verify(r.Context(), tokenString, ownerLookupFor(queries))+ if err != nil {+ if errors.Is(err, auth.ErrCloudPATInvalid) {+ slog.Warn("daemon_auth: cloud rejected mcn_ token", "path", r.URL.Path, "error", err)+ writeError(w, http.StatusUnauthorized, "invalid token")+ return+ }+ slog.Warn("daemon_auth: cloud pat verify unavailable", "path", r.URL.Path, "error", err)+ writeError(w, http.StatusServiceUnavailable, "cloud pat verifier unavailable")+ return+ }+ r.Header.Set("X-User-ID", identity.OwnerID)+ ctx := context.WithValue(r.Context(), ctxKeyDaemonAuthPath, DaemonAuthPathCloudPAT)+ next.ServeHTTP(w, r.WithContext(ctx))+ return+ }+// Fallback: PAT tokens ("mul_" prefix).if strings.HasPrefix(tokenString, "mul_") {hash := auth.HashToken(tokenString)diff --git a/server/internal/middleware/daemon_auth_test.go b/server/internal/middleware/daemon_auth_test.goindex 8502d65e38..a69f71ac55 100644--- a/server/internal/middleware/daemon_auth_test.go+++ b/server/internal/middleware/daemon_auth_test.go@@ -7,6 +7,7 @@ import ("testing""github.com/multica-ai/multica/server/internal/auth"+ db "github.com/multica-ai/multica/server/pkg/db/generated")// TestDaemonAuth_DaemonTokenCacheHit pins the daemon-token cache short-circuit:@@ -27,7 +28,7 @@ func TestDaemonAuth_DaemonTokenCacheHit(t *testing.T) {}, auth.AuthCacheTTL)var gotWS, gotDaemon, gotPath string- mw := DaemonAuth(nil, nil, cache) // nil queries — only safe on cache hit+ mw := DaemonAuth(nil, nil, cache, nil) // nil queries — only safe on cache hithandler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {gotWS = DaemonWorkspaceIDFromContext(r.Context())gotDaemon = DaemonIDFromContext(r.Context())@@ -66,7 +67,7 @@ func TestDaemonAuth_PATCacheHit(t *testing.T) {cache.Set(context.Background(), hash, "cached-user-id", auth.AuthCacheTTL)var gotUserID, gotPath string- mw := DaemonAuth(nil, cache, nil)+ mw := DaemonAuth(nil, cache, nil, nil)handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {gotUserID = r.Header.Get("X-User-ID")gotPath = DaemonAuthPathFromContext(r.Context())@@ -90,7 +91,7 @@ func TestDaemonAuth_PATCacheHit(t *testing.T) {}func TestDaemonAuth_MissingAuth(t *testing.T) {- mw := DaemonAuth(nil, nil, nil)+ mw := DaemonAuth(nil, nil, nil, nil)handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {t.Fatal("next must not be called")}))@@ -103,7 +104,7 @@ func TestDaemonAuth_MissingAuth(t *testing.T) {}func TestDaemonAuth_InvalidMDT_NilQueries(t *testing.T) {- mw := DaemonAuth(nil, nil, nil) // no caches, no DB+ mw := DaemonAuth(nil, nil, nil, nil) // no caches, no DBhandler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {t.Fatal("next must not be called")}))@@ -115,3 +116,154 @@ func TestDaemonAuth_InvalidMDT_NilQueries(t *testing.T) {t.Fatalf("expected 401, got %d", w.Code)}}++// TestDaemonAuth_MCN_NoVerifierConfigured pins the fail-closed+// behaviour when MULTICA_CLOUD_FLEET_URL is empty: an mcn_ token MUST+// be rejected at the prefix branch with 401, not silently fall+// through to the mul_/JWT paths (an mcn_ string would never match a+// valid PAT or JWT, but failing closed makes the contract explicit).+func TestDaemonAuth_MCN_NoVerifierConfigured(t *testing.T) {+ mw := DaemonAuth(nil, nil, nil, nil)+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ t.Fatal("next must not be called when verifier is unconfigured")+ }))+ req := httptest.NewRequest("POST", "/api/daemon/heartbeat", nil)+ req.Header.Set("Authorization", "Bearer mcn_anything")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)+ if w.Code != http.StatusUnauthorized {+ t.Fatalf("expected 401 with no verifier, got %d", w.Code)+ }+}++// TestDaemonAuth_MCN_ValidTokenSetsUserID confirms that on a successful+// Fleet verify, DaemonAuth surfaces owner_id as X-User-ID and tags the+// auth path as cloud_pat for telemetry. We use a stub Fleet here+// (no Redis) so the test runs without external services.+func TestDaemonAuth_MCN_ValidTokenSetsUserID(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{+ "valid": true,+ "owner_id": "01972f7e-7e8d-77ef-a13d-1b0ce3e9c001",+ "instance_id": "i-01"+ }`))+ }))+ defer srv.Close()++ verifier := auth.NewCloudPATVerifier(auth.CloudPATVerifierConfig{FleetBaseURL: srv.URL})++ var gotUser, gotPath string+ mw := DaemonAuth(nil, nil, nil, verifier)+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotUser = r.Header.Get("X-User-ID")+ gotPath = DaemonAuthPathFromContext(r.Context())+ w.WriteHeader(http.StatusOK)+ }))++ req := httptest.NewRequest("POST", "/api/daemon/heartbeat", nil)+ req.Header.Set("Authorization", "Bearer mcn_some_token")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if gotUser != "01972f7e-7e8d-77ef-a13d-1b0ce3e9c001" {+ t.Errorf("expected owner_id propagated as X-User-ID, got %q", gotUser)+ }+ if gotPath != DaemonAuthPathCloudPAT {+ t.Errorf("expected auth path %q, got %q", DaemonAuthPathCloudPAT, gotPath)+ }+}++// TestDaemonAuth_MCN_FleetSaysInvalid confirms that a valid:false+// Fleet response maps to 401 (not 503) — the token IS known to be bad,+// retrying won't help.+func TestDaemonAuth_MCN_FleetSaysInvalid(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"valid":false,"reason":"token_revoked"}`))+ }))+ defer srv.Close()++ verifier := auth.NewCloudPATVerifier(auth.CloudPATVerifierConfig{FleetBaseURL: srv.URL})+ mw := DaemonAuth(nil, nil, nil, verifier)+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ t.Fatal("next must not be called when fleet says invalid")+ }))++ req := httptest.NewRequest("POST", "/api/daemon/heartbeat", nil)+ req.Header.Set("Authorization", "Bearer mcn_revoked")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if w.Code != http.StatusUnauthorized {+ t.Fatalf("expected 401 for invalid token, got %d", w.Code)+ }+}++// TestDaemonAuth_MCN_FleetUnreachable confirms the Unavailable branch+// emits 503 — the daemon must distinguish "your token is bad" (401, drop+// it) from "cloud is down" (503, retry later) so a brief outage doesn't+// invalidate everyone's PAT.+func TestDaemonAuth_MCN_FleetUnreachable(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusInternalServerError)+ }))+ defer srv.Close()++ verifier := auth.NewCloudPATVerifier(auth.CloudPATVerifierConfig{FleetBaseURL: srv.URL})+ mw := DaemonAuth(nil, nil, nil, verifier)+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ t.Fatal("next must not be called when fleet is unavailable")+ }))++ req := httptest.NewRequest("POST", "/api/daemon/heartbeat", nil)+ req.Header.Set("Authorization", "Bearer mcn_x")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if w.Code != http.StatusServiceUnavailable {+ t.Fatalf("expected 503 when fleet is unavailable, got %d", w.Code)+ }+}+++// TestDaemonAuth_MCN_OwnerNotInLocalDB pins the new owner-existence+// guard end-to-end through the middleware. Cloud verifies the token+// successfully and returns an owner_id that does not exist in our+// local user table — DaemonAuth must reject with 401 (not 503) and+// MUST NOT call the next handler with a phantom X-User-ID.+func TestDaemonAuth_MCN_OwnerNotInLocalDB(t *testing.T) {+ pool := openPool(t)+ defer pool.Close()+ queries := db.New(pool)++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ // Owner_id is syntactically valid but not seeded in the DB.+ _, _ = w.Write([]byte(`{+ "valid": true,+ "owner_id": "00000000-0000-0000-0000-0000000feed1",+ "instance_id": "i-99"+ }`))+ }))+ defer srv.Close()++ verifier := auth.NewCloudPATVerifier(auth.CloudPATVerifierConfig{FleetBaseURL: srv.URL})++ mw := DaemonAuth(queries, nil, nil, verifier)+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ t.Fatal("next must not be called when owner_id has no local user")+ }))++ req := httptest.NewRequest("POST", "/api/daemon/heartbeat", nil)+ req.Header.Set("Authorization", "Bearer mcn_phantom_owner")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if w.Code != http.StatusUnauthorized {+ t.Fatalf("expected 401 when local user is missing, got %d", w.Code)+ }+}diff --git a/server/internal/middleware/owner_lookup.go b/server/internal/middleware/owner_lookup.gonew file mode 100644index 0000000000..d024ac2056--- /dev/null+++ b/server/internal/middleware/owner_lookup.go@@ -0,0 +1,59 @@+package middleware++import (+ "context"+ "errors"++ "github.com/jackc/pgx/v5"+ "github.com/multica-ai/multica/server/internal/auth"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// ownerLookupFor returns an auth.OwnerLookupFunc that asks the+// generated GetUser query whether `ownerID` is a real row in our+// `user` table. It is used by the mcn_ branches of Auth and+// DaemonAuth to confirm that Cloud's owner_id maps to a known local+// user before the verifier returns success / caches the result.+//+// Behaviour:+// - queries==nil → returns nil (no lookup; verifier skips step 3).+// This path only kicks in when a middleware is constructed+// without a DB handle, which only happens in tests that exercise+// the verifier wiring without a real database.+// - GetUser hits → (true, nil): owner_id is a known user.+// - pgx.ErrNoRows → (false, nil): owner_id is unknown.+// The verifier maps this to ErrCloudPATInvalid (reason+// "owner_unknown") without caching.+// - any other error → (_, err): treated as infrastructure failure;+// the verifier maps this to ErrCloudPATUnavailable so the+// middleware returns 503 (transient).+//+// Parsing the UUID is done via util.ParseUUID, which returns a zero+// UUID on a malformed input. A zero UUID will not match any real row,+// so the eventual GetUser call cleanly resolves to (false, nil) and+// the request is rejected — there is no need for a separate "looks+// like a UUID" precheck here. Cloud has already vetted the format+// before signing the verify response.+func ownerLookupFor(queries *db.Queries) auth.OwnerLookupFunc {+ if queries == nil {+ return nil+ }+ return func(ctx context.Context, ownerID string) (bool, error) {+ uuid, err := util.ParseUUID(ownerID)+ if err != nil {+ // Cloud returned something that doesn't parse as a UUID.+ // That's a contract violation, not a transient failure —+ // reject the token like any owner_unknown.+ return false, nil+ }+ _, err = queries.GetUser(ctx, uuid)+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return false, nil+ }+ return false, err+ }+ return true, nil+ }+}diff --git a/server/internal/middleware/owner_lookup_test.go b/server/internal/middleware/owner_lookup_test.gonew file mode 100644index 0000000000..a971b76d77--- /dev/null+++ b/server/internal/middleware/owner_lookup_test.go@@ -0,0 +1,152 @@+package middleware++import (+ "context"+ "errors"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// seedOwnerLookupUser inserts a fresh user row and returns its UUID+// as the canonical hyphenated string. Mirrors the lightweight fixture+// pattern used by setupResolverFixture so the lookup helper can be+// exercised against a real DB without dragging in the heavier handler+// fixture.+func seedOwnerLookupUser(t *testing.T, queries *db.Queries) string {+ t.Helper()+ ctx := context.Background()+ stamp := time.Now().UnixNano()+ user, err := queries.CreateUser(ctx, db.CreateUserParams{+ Name: "owner-lookup",+ Email: pgtypeUniqueEmail(stamp),+ })+ if err != nil {+ t.Fatalf("create user: %v", err)+ }+ t.Cleanup(func() {+ // Best-effort cleanup; another test parallel run will land+ // on a different stamp so a leak here doesn't bleed.+ _ = user+ })+ return uuidToString(user.ID)+}++// pgtypeUniqueEmail builds an email that is guaranteed unique within+// a test run so concurrent tests don't collide on the email UNIQUE+// index. Using nanosecond + a static suffix mirrors the patterns used+// elsewhere in the repo.+func pgtypeUniqueEmail(stamp int64) string {+ return time.Unix(0, stamp).UTC().Format("20060102T150405.000000000") + "@owner-lookup.test"+}++// TestOwnerLookupFor_NilQueries pins the contract that a middleware+// constructed without a *db.Queries handle skips the lookup entirely+// (Verify treats a nil OwnerLookupFunc as "no lookup configured").+// This path only exists to support unit tests that wire up the+// verifier without a real database.+func TestOwnerLookupFor_NilQueries(t *testing.T) {+ if got := ownerLookupFor(nil); got != nil {+ t.Fatalf("ownerLookupFor(nil) must return nil, got %T", got)+ }+}++// TestOwnerLookupFor_ExistingUser confirms the happy path: a real+// row in the user table resolves to (true, nil).+func TestOwnerLookupFor_ExistingUser(t *testing.T) {+ pool := openPool(t)+ defer pool.Close()+ queries := db.New(pool)++ userID := seedOwnerLookupUser(t, queries)+ t.Cleanup(func() {+ _, _ = pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userID)+ })++ lookup := ownerLookupFor(queries)+ exists, err := lookup(context.Background(), userID)+ if err != nil {+ t.Fatalf("lookup returned error: %v", err)+ }+ if !exists {+ t.Fatalf("expected user to be found")+ }+}++// TestOwnerLookupFor_MissingUser confirms that a syntactically valid+// UUID that does not match any row resolves to (false, nil) — the+// signal the verifier uses to emit reason="owner_unknown" and reject+// without caching.+func TestOwnerLookupFor_MissingUser(t *testing.T) {+ pool := openPool(t)+ defer pool.Close()+ queries := db.New(pool)++ lookup := ownerLookupFor(queries)+ // Random unused UUID — pgx.ErrNoRows territory.+ exists, err := lookup(context.Background(), "00000000-0000-0000-0000-0000deadbeef")+ if err != nil {+ t.Fatalf("missing user must NOT surface as a lookup error, got %v", err)+ }+ if exists {+ t.Fatalf("expected lookup to report user-not-found")+ }+}++// TestOwnerLookupFor_MalformedOwnerID confirms that an unparseable+// owner_id is treated as "user not found" (false, nil), not as a+// transient error. Cloud has already vetted the format on its side+// before signing the verify response, so a bad UUID here means+// either a contract violation or a forged response — either way the+// safe answer is to reject the token, same as a missing user.+func TestOwnerLookupFor_MalformedOwnerID(t *testing.T) {+ pool := openPool(t)+ defer pool.Close()+ queries := db.New(pool)++ lookup := ownerLookupFor(queries)+ exists, err := lookup(context.Background(), "not-a-uuid")+ if err != nil {+ t.Fatalf("malformed owner_id must NOT surface as a lookup error, got %v", err)+ }+ if exists {+ t.Fatalf("malformed owner_id must report user-not-found")+ }+}++// TestOwnerLookupFor_DBError mirrors the production failure mode the+// verifier maps to ErrCloudPATUnavailable: a query error (DB hung up,+// pool empty, etc.). Closing the pool before the call gives us a+// guaranteed real error rather than mocking the queries layer, which+// the rest of the suite doesn't do.+func TestOwnerLookupFor_DBError(t *testing.T) {+ pool := openPool(t)+ queries := db.New(pool)+ pool.Close() // intentional — every subsequent query must fail++ lookup := ownerLookupFor(queries)+ exists, err := lookup(context.Background(), "00000000-0000-0000-0000-000000000001")+ if err == nil {+ t.Fatal("expected real DB error to surface, got nil")+ }+ if exists {+ t.Fatal("DB error must not report user-found")+ }+ // And the error must NOT be classified as ErrNoRows by the+ // caller — that's how the verifier distinguishes "user really+ // doesn't exist" (401) from "DB is broken right now" (503).+ if errors.Is(err, errors.New("no rows")) {+ t.Fatalf("DB error must not look like ErrNoRows, got %v", err)+ }+}++// uuidToStringForOwnerLookup avoids depending on the existing+// uuidToString helper here in case its signature changes; the+// fixtures only need the canonical hyphenated form.+//+//nolint:unused // referenced via seedOwnerLookupUser indirectly.+func uuidToStringForOwnerLookup(u pgtype.UUID) string {+ return uuidToString(u)+}